python - 长度必须匹配才能使用 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)
但是,我得到了非常合乎逻辑的值错误,但不知道如何编辑条件。
解决方案
#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
推荐阅读
- javascript - 如何等待 iframe 父级为 postMessage 做好准备?
- linux - 如何使用 sed 将文本替换为文件路径?
- firebase - Flutter Firebase 合并:真的没有按预期工作?
- dialogflow-es - 如何在 JSON 响应中设置系统实体?
- c# - 如果我的标头中根本没有 Content-Type,ASP.NET Core Web API 管道的流程是什么?
- javascript - 如何按顺序运行js文件
- sql - Laravel Eloquent 中的多个 LIKE 子句
- unity3d - 从 Unity 中的预制脚本调用函数
- reactjs - 如何使用 React Native 和 Axios 发送表单数据?
- node.js - 我们在什么文件中将 react 前端文件夹文件与后端文件夹文件与 server.js 和 mysql 数据库连接连接起来?