python - 根据另一个数据框列值创建新的数据框列
问题描述
我有两个数据框df1
和df2
no plan current flag
0 abc1 249 30 Y/U
1 abc2 249 30 N
2 abc3 249 30 Y/D
和
plan offer
0 149 20
1 249 30
2 349 40
我想在其中添加一个额外的列,df1
以便它在比较df1['flag'] == 'Y/U'
中搜索下一个更高的数字。同样,相同的规则适用于较小的数字,其中标志为。(如果标志为N则保持正常)df2['offer']
df1['current']
Y/D
预期输出:
no plan current flag Pos
0 abc1 249 30 Y/U 40
1 abc2 249 30 N 30
2 abc3 249 30 Y/D 20
我尝试使用apply
.
df1['pos'] = (df1.apply(lambda x: next((z for (y, z) in zip(df2['plan'], df2['offer'])
if y > x['plan'] if z > x['current']), None), axis=1))
但它给出了考虑每个案例“Y/U”的结果。
解决方案
不使用计划,您可以达到这样的预期结果。你可以只使用一个列表。
offers = df2['offer'].sort_values().tolist()
def assign_pos(row, offers):
index = offers.index(row['current'])
if row['flag'] == "N":
row['pos'] = row['current']
elif row['flag'] == 'Y/U':
row['pos'] = offers[index + 1]
elif row['flag'] == 'Y/D':
row['pos'] = offers[index - 1]
return row
df1 = df1.apply(assign_pos, args=[offers], axis=1)
推荐阅读
- java - Android Studio,javax.net.ssl.SSLHandshakeException:不可接受的证书
- javascript - 弹跳球在碰撞时错过了一些平台
- python - 如何计算字母组合的出现次数?
- c# - OData 是否允许用户使用 IQueryable 查询 SQL EF 数据库?
- javascript - 如何实现滑动监听器?
- reactjs - 找不到所需的“intl”对象。
需要存在于组件祖先中 - c++ - 为什么一个方法对同一个变量有 const 和非 const 参数?
- docker - 我们可以使用 curl 命令将 docker 映像推/拉到 nexus 3 存储库吗
- c# - 如何以编程方式单击图钉?
- javascript - 如何从单独的 js 文件中调用角度 $scope 函数?