Python 3.x 对DatetimeIndexResampler类型执行操作时出错
我有一个时间序列数据框,希望找出每个记录中的日期与该数据框中最后一个(最大)日期之间的差异。但是获取错误-TypeError:-:“DatetimeIndex”和“SeriesGroupBy”的操作数类型不受支持。从错误中可以看出,数据帧不属于允许进行这些操作的“正确”类型。如何避免这种情况,或者可能以其他格式转换数据,以便能够执行该操作。下面是复制错误的示例代码Python 3.x 对DatetimeIndexResampler类型执行操作时出错,python-3.x,pandas,dataframe,time-series,Python 3.x,Pandas,Dataframe,Time Series,我有一个时间序列数据框,希望找出每个记录中的日期与该数据框中最后一个(最大)日期之间的差异。但是获取错误-TypeError:-:“DatetimeIndex”和“SeriesGroupBy”的操作数类型不受支持。从错误中可以看出,数据帧不属于允许进行这些操作的“正确”类型。如何避免这种情况,或者可能以其他格式转换数据,以便能够执行该操作。下面是复制错误的示例代码 import pandas as pd df = pd.DataFrame([[54.7,36.3,'2010-07-20'],[
import pandas as pd
df = pd.DataFrame([[54.7,36.3,'2010-07-20'],[54.7,36.3,'2010-07-21'],[52.3,38.7,'2010-07-26'],[52.3,38.7,'2010-07-30']],
columns=['col1','col2','date'])
df.date = pd.to_datetime(df.date)
df.index = df.date
df = df.resample('D')
print(type(df))
diff = (df.date.max() - df.date).values
我认为您需要首先按创建
DatetimeIndex
,因此如果按max
聚合,则获得连续值:
df = pd.DataFrame([[54.7,36.3,'2010-07-20'],
[54.7,36.3,'2010-07-21'],
[52.3,38.7,'2010-07-26'],
[52.3,38.7,'2010-07-30']],
columns=['col1','col2','date'])
df.date = pd.to_datetime(df.date)
df1 = df.set_index('date').resample('D').max()
#alternative if not duplicated datetimes
#df1 = df.set_index('date').asfreq('D')
print (df1)
col1 col2
date
2010-07-20 54.7 36.3
2010-07-21 54.7 36.3
2010-07-22 NaN NaN
2010-07-23 NaN NaN
2010-07-24 NaN NaN
2010-07-25 NaN NaN
2010-07-26 52.3 38.7
2010-07-27 NaN NaN
2010-07-28 NaN NaN
2010-07-29 NaN NaN
2010-07-30 52.3 38.7
然后减去索引本身的最大值,并将时间增量转换为天数:
预期产量是多少?为什么这里是
重采样
?数据框中每个记录的日期和最大日期之间的差异列表。例如,在我给出的示例中,如果我打印diff[0]->输出应为10。给出一个错误-AttributeError:无法访问“SeriesGroupBy”对象的可调用属性“rsub”,请尝试使用“apply”method@SanchitLatawa-但在我的代码中,没有重新采样
,没有分组方式
,但我想对时间序列重新采样以获取每日数据,因此问题就出现了。@SanchitLatawa-日期列中有时间?在“日期”列中,我显式地强制转换的日期在我的测试脚本中使用->pd.to_datetime(df.date)
df1['diff'] = (df1.index.max() - df1.index).days
print (df1)
col1 col2 diff
date
2010-07-20 54.7 36.3 10
2010-07-21 54.7 36.3 9
2010-07-22 NaN NaN 8
2010-07-23 NaN NaN 7
2010-07-24 NaN NaN 6
2010-07-25 NaN NaN 5
2010-07-26 52.3 38.7 4
2010-07-27 NaN NaN 3
2010-07-28 NaN NaN 2
2010-07-29 NaN NaN 1
2010-07-30 52.3 38.7 0