首页 > 解决方案 > 长度必须匹配才能使用 np.where 比较错误。如何正确设置条件?

问题描述

假设我有两个数据框

df1 喜欢(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)

但是,我得到了非常合乎逻辑的值错误,但不知道如何编辑条件。

标签: pythonpandas

解决方案


使用DataFrame.add

#convert id to index
df11 = df1.set_index('id')
#reshape data by pivot
df22 = df2.set_index(['id','val'])['num'].unstack(fill_value=0)
#alternative
#df22 = df2.pivot('id','val'm 'num').fillna(0)

#sum only intersection of index values 
df = df11.add(df22.loc[df11.index.intersection(df22.index)]).add_prefix('res')
print (df)
     res1  res2
id             
id1    35    17
id2    14    15
id3    15    10

推荐阅读