Python 从多个数据帧创建列
我需要根据Python 从多个数据帧创建列,python,pandas,Python,Pandas,我需要根据dataframe字段的值和具有一定速率的查找dataframe创建一些新列 具有df1as zone hh hhind 0 14 112.0 3.4 1 15 5.0 4.4 2 16 0.0 1.0 和一个查找df作为 ind per1 per2 per3 per4 0 1.0 1.000 0.000 0.000 0.000 24 3.
dataframe
字段的值和具有一定速率的查找dataframe
创建一些新列
具有df1
as
zone hh hhind
0 14 112.0 3.4
1 15 5.0 4.4
2 16 0.0 1.0
和一个查找df作为
ind per1 per2 per3 per4
0 1.0 1.000 0.000 0.000 0.000
24 3.4 0.145 0.233 0.165 0.457
34 4.4 0.060 0.114 0.075 0.751
如何根据df1.hhind
和lookup.ind
乘以lookup.per1
更新df1.hh1
zone hh hhind hh1
0 14 112.0 3.4 16.240
1 15 5.0 4.4 0.300
2 16 0.0 1.0 0.000
现在我通过合并表格和做算术得到结果
r = pd.merge(df1, look_up, left_on="hhind", right_on="ind")
r["hh1"] = r.hh *r.per1
我想知道是否有更直接的方法通过不合并表来实现这一点?您可以首先将hhind和ind分别设置为df1
和查找
数据帧的索引轴。然后,将hh中的相应元素和per1元素相乘
将这些结果映射到列hhind,并稍后将其分配到新列,如图所示:
mapper = df1.set_index('hhind')['hh'].mul(look_up.set_index('ind')['per1'])
df1.assign(hh1=df1['hhind'].map(mapper))
另一种解决方案:
df1['hh1'] = (df1['hhind'].map(lambda x: look_up[look_up["ind"]==x]["per1"])) * df1['hh']