【问题标题】:python dataframe inner join by time period按时间段的python数据框内部连接
【发布时间】:2020-11-03 05:40:53
【问题描述】:
我有两个数据集
df A
index time col1
0 2020-10-31 16:30:30 10
1 2020-10-31 16:40:30 40
df B
index time col2
0 2020-10-31 16:31:30 10
我想在时间 diff
【问题讨论】:
标签:
python
pandas
dataframe
join
【解决方案1】:
如果每 2 分钟只有 1 个值,您可以尝试使用 .resample():
示例代码:
from io import StringIO
import pandas as pd
# create sample data as in example given
textA = """
time col1
2020-10-31T16:30:30 10
2020-10-31T16:40:30 40
"""
textB = """
time col2
2020-10-31T16:31:30 10
"""
# put sample data in dataframes
dfA = pd.read_csv(StringIO(textA), header=0, sep='\s+')
dfB = pd.read_csv(StringIO(textB), header=0, sep='\s+')
dfA['time'] = pd.to_datetime(dfA['time'])
dfB['time'] = pd.to_datetime(dfB['time'])
# for resampling the index needs to be a datetime
dfA = dfA.set_index('time')
dfB = dfB.set_index('time')
# resample rows to every 2 minutes
dfA = dfA.resample('2min').mean()
dfB = dfB.resample('2min').mean()
# join dataframes based on resampled time
# and drop all rows that only have na values
dfA.join(dfB).dropna(how='all')