首页 > 解决方案 > 使用一个查找数据框中的索引和列在另一个数据框中创建一个新列

问题描述

我有一个用于查找值的数据框:

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(... 逻辑,但感觉也不对,而且它的可扩展性也不是很好。

标签: pandasdataframe

解决方案


您可以stack在收入列和位置列rw2上使用,例如:reindexdf

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

推荐阅读