如何检索两列之间最接近的数字匹配行

问题描述 投票:0回答:1

早晨好

我被一个短项目卡住了,我有两个DF,看起来像。

df1:

date city region customers sellers
2020-05-15 London A 125 25
2020-05-14 Paris B 1233 50
2020-05-01 London A 1260 58
2020-05-02 Paris B 250 41

df2:

date city region customers
2020-05-20 London A 1250
2020-05-21 Paris B 123

df2中所有的日期都不在df1中(预测与实际)。

因此,我把两者合并成这样。

new_df = pd.merge(df1, df2, how='left', left_on=['city','region'], right_on = ['city','region'])

结果是:

我想实现的是用顾客的数量来获取最接近customer_x列的行。

date_x city_x region_x customers_x sellers_x date_y city_y region_y customers_y
2020-05-15 London A 125 25 NaN London A 1250
2020-05-14 Paris B 1233 50 NaN Paris B 123
2020-05-01 London A 1260 58 NaN London A 1250
2020-05-02 Paris B 250 41 NaN Paris B 123

我想达到的目的是用customers_y的数字得到与customers_x列最接近的行。

在这个例子中,这将是:final_df。

2020-05-01 London A 1260 58 NaN London A 1250
2020-05-02 Paris B 250 41 NaN Paris B 123

所以我想我需要做客户x和y之间的delta,然后只检索两者之间的最小值列,但我不知道如何做...欢迎任何帮助。谢谢你的帮助

python pandas numpy dataframe closest
1个回答
0
投票

请尝试

df = pd.merge(df2, df1, how='left', on=['date', 'city','region','customers'])

0
投票

你可以做 merge_asof:

# sort dataframe for merge_asof
df2 = df2.sort_values('customers')
df1 = df1.sort_values('customers')

final_df = (pd.merge_asof(df2, df1.reset_index(),
                          by=['city','region'], on='customers',
                          suffixes=['','_1'],
                          direction='nearest'
                         )
              .assign(customer_1=lambda x: x['index'].map(df1['customers']))
              .drop('index',axis=1)
     )

产出:

         date    city region  customers      date_1  sellers  customer_1
0  2020-05-21   Paris      B        123  2020-05-02       41         250
1  2020-05-20  London      A       1250  2020-05-01       58        1260
© www.soinside.com 2019 - 2024. All rights reserved.