【问题标题】:Length must match to compare error using np.where. How to set up condition properly?长度必须匹配才能使用 np.where 比较错误。如何正确设置条件?
【发布时间】: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)

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

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用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
    

    【讨论】:

      猜你喜欢
      • 2017-03-25
      • 1970-01-01
      • 2020-05-01
      • 2019-08-24
      • 2017-04-12
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      相关资源
      最近更新 更多