Python:根据条件将信息从一个数据帧提取到另一个数据帧(具有不同的长度)

Python: Extracting information from one dataframe to another (with different lengths) based on condition

我有两个长度不同的数据帧(df1 和 df2)(25696 和 28)。尽管如此,它们有两列共享相同的信息(日期和 day_period)。

这里是数据预览:

df1 
>>
    id timestamp                 col1   col2    day_period  date
0    A  2021-06-09 08:12:18.000  12     32      Morning     2021-06-09
1    A  2021-06-09 08:12:18.000  5      32      Morning     2021-06-09
2    A  2021-06-09 08:12:18.587  54     34      Morning     2021-06-09
3    A  2021-06-09 08:12:18.716  56     53      Morning     2021-06-09 
4    A  2021-06-09 08:12:33.000  34     23      Morning     2021-06-09


df2
>>
    date       day_period   temperature atmospheric_pressure    wind_speed  humidity
0   2021-06-09  Night       15          30.1                    2.6         94
1   2021-06-09  Morning     14          30.1                    3.2         90
2   2021-06-09  Day         18          30.1                    4.2         60
3   2021-06-09  Evening     19          30.0                    2.7         66
4   2021-06-10  Night       16          30.0                    3.6         81

我的目标是在 day_period 和日期相同时将 df2 的所有其他列合并到 df1。对于 df1 中的预览,来自 df2[["temperature", "atmospheric_pressure", "wind_speed", "humidity"]] 的值将对日期为 2021-06-09 和 day_period Morning 的所有观察重复。考虑到长度的差异,如何实现?

所以,我的目标输出是这样的:

    id timestamp                 col1   col2    day_period  date        temperature    atmospheric_pressure  wind_speed  humidity
0    A  2021-06-09 08:12:18.000  12     32      Morning     2021-06-09  15             30.1                  2.6           94
1    A  2021-06-09 08:12:18.000  5      32      Morning     2021-06-09  14             30.1                  3.2           90
2    A  2021-06-09 08:12:18.587  54     34      Morning     2021-06-09  18             30.1                  4.2           60
3    A  2021-06-09 08:12:18.716  56     53      Morning     2021-06-09  19             30.0                  2.7           66
4    A  2021-06-09 08:12:33.000  34     23      Morning     2021-06-09  16             30.0                  3.6           81

请注意,df1 中有一个 ID 列,因此日期仅按 ID 按时间顺序排列。

您想加入,例如使用 merge:

df1.merge(df2, left_on=['date', 'day_period'], right_on=['date', 'day_period'])

输出:

  id                timestamp  col1  col2 day_period        date  temperature  atmospheric_pressure  wind_speed  humidity
0  A  2021-06-09 08:12:18.000    12    32    Morning  2021-06-09           14                  30.1         3.2        90
1  A  2021-06-09 08:12:18.000     5    32    Morning  2021-06-09           14                  30.1         3.2        90
2  A  2021-06-09 08:12:18.587    54    34    Morning  2021-06-09           14                  30.1         3.2        90
3  A  2021-06-09 08:12:18.716    56    53    Morning  2021-06-09           14                  30.1         3.2        90
4  A  2021-06-09 08:12:33.000    34    23    Morning  2021-06-09           14                  30.1         3.2        90