首页 > 解决方案 > 根据另一个数据框列值创建新的数据框列

问题描述

我有两个数据框df1df2

     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”的结果。

标签: pythonpandasdataframe

解决方案


不使用计划,您可以达到这样的预期结果。你可以只使用一个列表。

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)

推荐阅读