【问题标题】:Pandas Using a Datetime column in a Dataframe to have the nearest match comparing with multiple Datetime columnsPandas 使用 Dataframe 中的 Datetime 列与多个 Datetime 列进行最接近的匹配
【发布时间】:2020-01-22 12:14:09
【问题描述】:

使用 Dataframe 中的 Datetime 列与多个 Datetime 列进行最接近的匹配

df1 = pd.DataFrame({'Datetime_1' : ['2/4/2015 2:00:00','3/5/2015 3:00:00','4/3/2015 4:00:00'],
                    'Datetime_2' : ['2/3/2015 2:00:00','3/3/2015 3:00:00','4/3/2015 4:10:00'],
                    'Datetime_3' : ['2/4/2015 2:00:10','3/5/2015 3:20:00','4/3/2015 4:10:10']})

    Datetime_1          Datetime_2          Datetime_3         Amount
0   2/4/2015 2:00:00    2/3/2015 2:00:00    2/4/2015 2:00:10    100
1   3/5/2015 3:00:00    3/3/2015 3:00:00    3/5/2015 3:20:00    700
2   4/3/2015 4:00:00    4/3/2015 4:10:00    4/3/2015 4:10:10    1000

df2 = pd.DataFrame({'Datetime_1' : ['2/4/2015 2:00:05','3/5/2015 3:11:00','4/3/2015 4:00:01']})

       Datetime_1       Values
0   2/4/2015 2:00:05    10
1   3/5/2015 3:11:00    70
2   4/3/2015 4:10:01    100

预期输出

 Datetime_1              Nearest_Match_df1     Values   Amount    MatchColumn 
 2/4/2015 2:00:05        2/4/2015 2:00:00      10       100       Datetime_1
 3/5/2015 3:11:00        3/5/2015 3:20:00      70       700       Datetime_3
 4/3/2015 4:10:01        4/3/2015 4:10:00      100      1000      Datetime_2

【问题讨论】:

  • 您想逐行比较两个数据帧中的时间,还是 df2 中的所有时间与 df1 中的所有时间进行比较
  • @QuangHoang 逐行

标签: python pandas datetime merge pandas-groupby


【解决方案1】:

您可以在修改df1 后使用merge_asof 来获取单个列中的所有日期。为此,您 set_index 列 Amount 然后 stack 数据框,然后 reset_indexrename 列以匹配预期输出并复制列和日期以执行合并。

df_res = pd.merge_asof( df2,
                        df1.set_index('Amount').stack().reset_index(name='Nearest_Match_df1')
                           .rename(columns={'level_1': 'MatchColumn'})
                           .assign(Datetime_1=lambda x: x.Nearest_Match_df1)
                           .sort_values(by=['Datetime_1']),
                        on = ['Datetime_1'], direction='nearest')

print (df_res)
           Datetime_1  values  Amount MatchColumn   Nearest_Match_df1
0 2015-02-04 02:00:05      10     100  Datetime_1 2015-02-04 02:00:00
1 2015-03-05 03:11:00      70     700  Datetime_3 2015-03-05 03:20:00
2 2015-04-03 04:00:01     100    1000  Datetime_1 2015-04-03 04:00:00

注意:所有列必须是Datetime 类型

【讨论】:

  • 这个 'on = ['Datetime_1']' 指的是 df1 或 df2 还是 bioth。如果 df1 的 Date 列是 Datetime,它将如何工作?
  • @heykay 因为df2中日期列的名称是Datetime_1,所以我在修改df1的形状时在assign中使用了这个名称,以便能够对这一列进行合并,有意义吗?
  • 另一种情况,如果两个 df 中的 Value 和 Amount 与唯一标识符相同,该怎么办。这将如何运作?
  • @heykay 你的意思是你想先合并列 Amount 和 Value 中的相同值?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-23
  • 1970-01-01
相关资源
最近更新 更多