gpt4 book ai didi

python - 从多个数据帧创建列

转载 作者:行者123 更新时间:2023-12-01 03:18:16 24 4
gpt4 key购买 nike

我需要根据 dataframe 字段的值创建一些新列,并使用某些费率查找 dataframe

df1作为

    zone    hh      hhind
0 14 112.0 3.4
1 15 5.0 4.4
2 16 0.0 1.0

look_up 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.hhindlookup.ind< 的 look_up.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

我想知道是否有更直接的方法来通过不合并表格来实现此目的?

最佳答案

您可以首先将 hindind 分别设置为 df1look_up 数据帧的索引轴。然后,将 hhper1 中的相应元素逐个相乘。

将这些结果映射到 hind 列,并稍后将它们分配给新列,如下所示:

mapper = df1.set_index('hhind')['hh'].mul(look_up.set_index('ind')['per1'])
df1.assign(hh1=df1['hhind'].map(mapper))

enter image description here

关于python - 从多个数据帧创建列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42255330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com