我有两个熊猫DataFrames:df1key id count100 9821 7200 9813 10df2nodekey nodeid 100 9821 200 9813 如果df2中的nodekey + nodeid与df1中的key + id相匹配,则df1中的count必须设置为0。key id count100 9821 0200 9813 0我尝试了以下操作(仅在键和节点键上进行匹配,作为测试),但是收到错误消息:df1['count']=np.where((df1.key == df2.nodekey),0)ValueError: either both or neither of x and y should be given有什么建议吗?
2 回答
茅侃侃
TA贡献1842条经验 获得超21个赞
这应该工作
df1.loc[df1[['key', 'id']].transform(tuple,1).isin(df2[['nodekey', 'nodeid']].transform(tuple,1)), "count"] = 0
基本上是在用
df.loc[mask, 'count']=0
这里mask
是True
对其中的元组行('key', 'id')
任何元组相匹配('nodekey', 'nodeid')
炎炎设计
TA贡献1808条经验 获得超4个赞
使用左合并合并数据帧(在df1中但在df2中不存在的行将用nans填充):
combined = df1.merge(df2, left_on=['key', 'id'],
right_on=['nodekey', 'nodeid'], how='left')
更新非nan以下行的计数:
combined.loc[combined.nodekey.notnull(), 'count'] = 0
清理不需要的列:
combined.drop(['nodekey', 'nodeid'], axis=1, inplace=True)
# key id count
#0 100 9821 0
#1 200 9813 0
#2 300 9855 7
添加回答
举报
0/150
提交
取消