python - 将 pandas DataFrame 行保留在 df2 中,并为 df1 中的每一行保留 timedelta

标签 python pandas dataframe

我有两个 pandas 数据框。我想保留 df2 中的所有行,其中 Type 等于 df1 中的 Type AND Date 位于 df1 中的 Date 之间(- 1 天或 + 1 天)。我怎样才能做到这一点?

df1

   IBSN  Type          Date
0     1     X    2014-08-17
1     1     Y    2019-09-22

df2

   IBSN  Type          Date
0     2     X    2014-08-16
1     2     D    2019-09-22
2     9     X    2014-08-18
3     3     H    2019-09-22
4     3     Y    2019-09-23
5     5     G    2019-09-22

资源

   IBSN  Type          Date
0     2     X    2014-08-16 <-- keep because Type = df1[0]['Type'] AND Date = df1[0]['Date'] - 1
1     9     X    2014-08-18 <-- keep because Type = df1[0]['Type'] AND Date = df1[0]['Date'] + 1
2     3     Y    2019-09-23 <-- keep because Type = df1[1]['Type'] AND Date = df1[1]['Date'] + 1

最佳答案

这应该可以做到:

import pandas as pd
from datetime import timedelta

# create dummy data
df1 = pd.DataFrame([[1, 'X', '2014-08-17'], [1, 'Y', '2019-09-22']], columns=['IBSN', 'Type', 'Date'])
df1['Date'] = pd.to_datetime(df1['Date'])  # might not be necessary if your Date column already contain datetime objects

df2 = pd.DataFrame([[2, 'X', '2014-08-16'], [2, 'D', '2019-09-22'], [9, 'X', '2014-08-18'], [3, 'H', '2019-09-22'], [3, 'Y', '2014-09-23'], [5, 'G', '2019-09-22']], columns=['IBSN', 'Type', 'Date'])
df2['Date'] = pd.to_datetime(df2['Date'])  # might not be necessary if your Date column already contain datetime objects


# add date boundaries to the first dataframe
df1['Date_from'] = df1['Date'].apply(lambda x: x - timedelta(days=1))
df1['Date_to'] = df1['Date'].apply(lambda x: x + timedelta(days=1))

# merge the date boundaries to df2 on 'Type'. Filter rows where date is between
# data_from and date_to (inclusive). Drop 'date_from' and 'date_to' columns
df2 = df2.merge(df1.loc[:, ['Type', 'Date_from', 'Date_to']], on='Type', how='left')
df2[(df2['Date'] >= df2['Date_from']) & (df2['Date'] <= df2['Date_to'])].\
    drop(['Date_from', 'Date_to'], axis=1)

请注意,根据您的逻辑,df2 中的第 4 行(3 Y 2014-09-23)不应保留,因为其日期(2014 年)不在 df1 中的给定日期(2019 年)之间。

关于python - 将 pandas DataFrame 行保留在 df2 中,并为 df1 中的每一行保留 timedelta,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59870706/

相关文章:

python - 在 Pandas 中查找相同连续元素的 block (及其大小)

python - 根据 Pandas 中的列表删除行

Python 代码性能随线程而降低

python - Pyplot set_xticks 无法按预期工作

Python 多处理在本地运行比在集群上运行更快(slurm)

python - Pandas 在数据框和系列(列)之间相乘

python - 添加内联后 Django 的运行服务器挂起。 1.8版本

python - 快速将 Pandas 列乘以年度系数

python - 将 python pandas df 替换为基于条件的第二个数据帧的值

python - Pandas 数据框列意外乱序