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

问题描述 投票:0回答:1

我有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?

python pandas dataframe concat
1个回答
1
投票

你的解决方案工作得很好,只是需要升级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

0
投票

你需要 concat 两个数据帧 df1df2. 在你的命令中,你已经连通了 total_dfdf1.

要么使用 df.append:

total_df = df1.append(df2)

   id booleanValue
0   0         True
1   1         False
0   2         True
1   3         NaN

pd.concat,像这样。

total_df = pd.concat([df1,df2])

   id booleanValue
0   0         True
1   1         False
0   2         True
1   3         NaN
© www.soinside.com 2019 - 2024. All rights reserved.