【问题标题】:Error while performing operation on DatetimeIndexResampler type对 DatetimeIndexResampler 类型执行操作时出错
【发布时间】:2020-03-14 19:12:00
【问题描述】:

我有一个时间序列数据框,想找出每条记录中的日期与该数据框中的最后一个(最大)日期之间的差异。但出现错误 - TypeError:不支持的操作数类型 -:'DatetimeIndex' 和 'SeriesGroupBy'。从错误看来,数据框不是允许这些操作允许的“正确”类型。我怎样才能避免这种情况或可能将数据转换为其他格式才能进行操作。下面是重现错误的示例代码

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

【问题讨论】:

  • 预期输出是什么?为什么在这里resample
  • 数据框中每条记录的日期和最大日期之间的差异列表。例如,从我给出的示例中,如果我打印 diff[0] -> 输出应该是 10。

标签: python-3.x pandas dataframe time-series


【解决方案1】:

我认为您需要先由DataFrame.set_index 创建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

然后将索引的最大值与自身相减,并将 timedeltas 转换为天数 TimedeltaIndex.days

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

【讨论】:

  • 给出错误 - AttributeError: 无法访问 'SeriesGroupBy' 对象的可调用属性 'rsub',尝试使用 'apply' 方法
  • @SanchitLatawa - 但在我的代码中没有resample,没有groupby
  • 但我想重新采样时间序列以获取每日数据,因此出现了问题。
  • @SanchitLatawa - 日期列中有时间?
  • “日期”列中的日期,我明确地在我的测试脚本中使用 -> pd.to_datetime(df.date)
猜你喜欢
  • 1970-01-01
  • 2018-02-22
  • 1970-01-01
  • 2014-06-25
  • 1970-01-01
  • 1970-01-01
  • 2019-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多