简体   繁体   English

如何在 Python Pandas 中的某个条件下合并 3 个关于日期值的数据帧?

[英]How to merge 3 DataFrames under certain conditions about date value in one of them in Python Pandas?

I have 3 DataFrames in Python Pandas like below:我在 Python Pandas 中有 3 个数据帧,如下所示:

df1 (ID - int, TIME - datetime) df1 (ID - int, TIME - 日期时间)

ID  | TIME
----|------
123 | 2022-07-18
333 | 2022-07-22
444 | 2022-07-19
... | ...

df2 (both int) df2(均为整数)

ID  | VALUE
----|------
123 | 556 
333 | 12  
444 | 88  
... | ...

df3 (both int) df3(均为整数)

ID  | TIME
----|------
123 | 11114 
333 | 2
444 | 23 
... | ...

And I need to make a merge:我需要进行合并:

  • if TIME in df1 is < 2022-07-19 merge df1 with df2如果 df1 中的 TIME < 2022-07-19 将 df1 与 df2 合并
  • if TIME in df1 is >= 2022-07-19 merge df1 with df3如果 df1 中的 TIME >= 2022-07-19 将 df1 与 df3 合并

So as a result I need something like below:因此,我需要以下内容:

ID  | TIME       | VALUE
----|------------|-------
123 | 2022-07-18 | 556
333 | 2022-07-22 | 2
444 | 2022-07-19 | 23
... | ...        | ...

How can I do that in Python Pandas?如何在 Python Pandas 中做到这一点? OF course merge by ID col:)当然通过 ID col 合并:)

If there are same index, same order ID in all 3 DataFrames use numpy.where :如果有相同的索引,则所有 3 个 DataFrame 中的相同订单ID使用numpy.where

df1['VALUE'] = np.where(df1['TIME'] < '2022-07-19', df2['VALUE'], df3['VALUE'])

If not use Series.map :如果不使用Series.map

df1['VALUE'] = np.where(df1['TIME'] < '2022-07-19', 
                        df1['ID'].map(df2.set_index('ID')['VALUE']), 
                        df1['ID'].map(df3.set_index('ID')['VALUE']))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM