【发布时间】:2020-04-23 07:31:54
【问题描述】:
假设我有两个数据框
df1 like (id 是索引):
**id** | 1 | 2 |
**id1** | 23| 12|
**id2** | 14| 5 |
**id3** | 5 | 10|
df2 喜欢:
id | val |num|
id1 | 1 | 12|
id1 | 2 | 5 |
id2 | 2 | 10|
id3 | 1 | 10|
id5 | 2 | 5|
我应该如何设置 np.where() 以便满足以下条件:
for each id in DF1 add "num" value from DF2 where number in 'val' column == column name, if theres no such value => add 0
这样就达到了下一个结果:
id | res1 | res2 |
id1 | 35 | 17 |
id2 | 14 | 15 |
id3 | 15 | 10 |
由于我逐列迭代我的 np.where 条件如下所示:
np.where((df2.id.isin(df1.index)) & (df.val== df.columns.values[i]), df2['num'], 0)
但是,我得到了非常合乎逻辑的值错误,但不知道如何编辑条件。
【问题讨论】: