gpt4 book ai didi

python - 添加来自两个不同数据帧的两列,所有其他列都相同

转载 作者:行者123 更新时间:2023-11-28 21:37:21 25 4
gpt4 key购买 nike

如何从两个不同的 DataFrame 添加两列,其中除了我想要添加的列之外,所有列都相等?

请参阅下面的示例代码:

#IN:
import pandas as pd
import numpy as np
#Observe that 'col2' in both dataframes are equal
df1 = pd.DataFrame({'col1': [3.2, 4.4, 6.5, np.NaN], 'col2': [1.2, 2.2, np.NaN, 5.7]})

col1 col2
0 3.2 1.2
1 4.4 2.2
2 6.5 nan
3 nan 5.7

df2 = pd.DataFrame({'col1': [1.0, 2.0, 3.0, 4.0], 'col2': [1.2, 2.2, np.NaN, 5.7]})

col1 col2
0 1.0 1.2
1 2.0 2.2
2 3.0 nan
3 4.0 5.7

# new_df = [INSERT SOME MAGIC FUNCTION HERE]
# I tried: new_df = df1.add(df2, level='col1')
# but obviously that did not work

#OUT (This is what I want):
print(new_df)

col1 col2
0 4.2 1.2
1 6.4 2.2
2 9.5 nan
3 4.0 5.7

观察np.NaN + some_float = some_float

最佳答案

这是一种方法。添加 2 个系列时请记住 fillna(0)

res = pd.DataFrame({'col1': df1['col1'].fillna(0) + df2['col1'].fillna(0),
'col2': df1['col2']})

print(res)

# col1 col2
# 0 4.2 1.2
# 1 6.4 2.2
# 2 9.5 NaN
# 3 4.0 5.7

关于python - 添加来自两个不同数据帧的两列,所有其他列都相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49692483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com