我有 2 个数据帧 df1
和 df2
包含相同项目的信息,但 df1
中的某些元素无法出现在 中>df2
。
例如:
df1
id count
0 5 124
1 3 136
2 7 12
3 2 345
df2
id count
0 5 65
1 7 3
我想仅计算存在的元素的分数df1['count']/df2['count']
,否则计算0
df3
id count
0 5 1.91
1 3 0
2 7 4
3 2 0
最佳答案
使用map
对于新的Series
,除以 div
最后一个不匹配的 id
被创建为 NaN
,并被 fillna
替换。 :
df1['count'] = df1['count'].div(df1['id'].map(df2.set_index('id')['count'])).fillna(0)
print (df1)
id count
0 5 1.907692
1 3 0.000000
2 7 4.000000
3 2 0.000000
详细信息:
print (df1['id'].map(df2.set_index('id')['count']))
0 65.0
1 NaN
2 3.0
3 NaN
Name: id, dtype: float64
关于Python:如何在两个数据帧之间进行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50566259/