pandas - 使用一个查找数据框中的索引和列在另一个数据框中创建一个新列
问题描述
我有一个用于查找值的数据框:
ruralw2 = [[0.1,0.3,0.5], [0.1,0.2,0.8], [0.1,0.2,0.7], [0.1,0,0.3]]
rw2 = pd.DataFrame(data=ruralw2, columns=['city','suburbs','rural'],index=['low','med','high','v-high'])
然后我有另一个数据框,我想根据 rw2 数据框中的数据获取“p”值:
df = pd.DataFrame(columns=['location','income','p'])
df['location'] = ['city','city','suburbs','rural','rural']
df['income'] = ['low','med','high','v-high','med']
我期望的是:
可以使用 for 循环,但它在 Pandas 中是一种反模式,我认为应该有更好的方法。
for i in np.arange(df.shape[0]):
df['p'][i] = rw2.loc[df['income'][i],df['location'][i]]
另一种可能性是写很长的 np.where(... 逻辑,但感觉也不对,而且它的可扩展性也不是很好。
解决方案
您可以stack
在收入列和位置列rw2
上使用,例如:reindex
df
df['p'] = rw2.stack().reindex(df[['income', 'location']]).to_numpy()
location income p
0 city low 0.1
1 city med 0.1
2 suburbs high 0.2
3 rural v-high 0.3
4 rural med 0.8
推荐阅读
- excel - 在vba中使用带有多个条件的if语句循环遍历给定范围内的每一行
- json - 如何使用 Azure ARM 模板从 keyvault 传递秘密值
- spring-security - Spring hybris 中基于路径的漏洞
- docker - 来自多级 Dockerfiles 的 `npm build` 和 `COPY --from` 失败并显示 `COPY failed: stat /mnt/data/docker/overlay2/xxxxx/merged/app/build
- c# - 在 ASP.NET MVC 和 Azure 中注册后发送电子邮件确认延迟
- variables - 使用变量创建文件夹时如何修复括号扩展
- c# - 在 Navigation.GoBack() 上重新加载页面后执行代码
- symfony - Symfony + Doctrine onFlush - 如何跳过实体的插入和更新
- swift - var testID = String() 和 var testID 有什么区别:String = ""
- vue.js - 如何在 App.vue 文件中创建数据属性?