我有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,因为 可空的布尔数据类型 劳动 pandas 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