连接数据帧,同时确保布尔值未转换为整数

Concatenate dataframes while making sure boolean value is not converted into integer

我有 df1 和 df2,我想在 for 循环中合并到一个数据帧中。 2个数据框是相同的 df1 看起来像这样

id booleanValue
0     True
1     False

df2 看起来像这样

id booleanValue
2     True
3     np.nan

我做到了

total_df = pd.Dataframe()
total_df = pd.concat([total_df, df1], ignore_index=True, sort=False)

我希望得到

id booleanValue
0     True
1     False
2     True
3     NaN

但我得到了

id booleanValue
0     0.0
1     1.0
2     0.0
3     0.0

有没有办法连接起来,这样布尔值就不会被转换成整数,并且 np.nan 将保持为 np.nan?

您的解决方案运行良好,只需要升级 pandas,因为 Nullable Boolean Data Typepandas 1.0.0+:

开始工作
df1['booleanValue'] = df1['booleanValue'].astype('boolean')
df2['booleanValue'] = df2['booleanValue'].astype('boolean')

total_df = pd.concat([df1, df2], ignore_index=True, sort=False)
print (total_df.dtypes)
id                int64
booleanValue    boolean
dtype: object

print (total_df)
   id  booleanValue
0   0          True
1   1         False
2   2          True
3   3          <NA>

如果不转换为 boolean 的解决方案 - 获取 object dtype:

total_df = pd.concat([df1, df2], ignore_index=True, sort=False)
print (total_df)
   id booleanValue
0   0         True
1   1        False
2   2         True
3   3          NaN

print (total_df.dtypes)
id               int64
booleanValue    object
dtype: object