3 回答
TA贡献1852条经验 获得超1个赞
我使用 add 方法和combine_first方法来获得结果。select_dtypes允许基于数据类型的操作。
(df1
.add(df2.select_dtypes(include='number'))
.combine_first(df1)
)
a b c d
0 2 2 dd 2
1 2 2 ee 2
2 2 2 ff 2
TA贡献1785条经验 获得超8个赞
尝试这个 :
column_names = df1.columns.tolist()
columnTotal_dict = {}
for name in colum_names:
try:
df1[[name]] = df1[[name]].astype(int)
df2[[name]] = df2[[name]].astype(int)
sumCol_a_df1 = df1['a'].sum()
sumCol_a_df2 = df2['a'].sum()
columnTotal_dict[name] = sumCol_a_df1 + sumCol_a_df2
except ValueError:
print("Data in this column are not of type int. Skipping")
TA贡献1821条经验 获得超4个赞
可以试试(假设列c可以取自第一个数据框)
>>> mask = ['a', 'b', 'd']
>>> df_out = df1[mask] + df2[mask]
>>> df_out['c'] = df1['c']
>>> df_out
a b d c
0 2 2 2 dd
1 2 2 2 ee
2 2 2 2 ff
添加回答
举报