簡體   English   中英

重新采樣pandas列datetime

[英]Resampling pandas columns datetime

(我認為)我有一個數據集,其中的列表示datetime時間間隔

列在日期時間轉換為:

    for col in df.columns:
        df.rename({col: pd.to_datetime(col, infer_datetime_format=True)}, inplace=True)

然后,我需要使用mean將列(年份和月份'2001-01') resample為四分之一

我試過了

df = df.resample('1q', how='mean', axis=1)

DataFrame還有一個多索引集['RegionName', 'County']

但我得到錯誤:

Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'

問題是在to_datetime函數中還是在錯誤的采樣中?

(我認為)您重命名每個列頭而不是使整個列對象為DatetimeIndex

試試這個:

df.columns = pd.to_datetime(df.columns)

然后運行resample


注意:
轉換為DatetimeIndex后,我會用period來完成。 這樣,您可以在列標題中獲得句點,而不是季度的結束日期。

df.groupby(df.columns.to_period('Q'), axis=1).mean()

演示

df = pd.DataFrame(np.arange(12).reshape(2, -1),
                  columns=['2011-01-31', '2011-02-28', '2011-03-31',
                           '2011-04-30', '2011-05-31', '2011-06-30'])

df.columns = pd.to_datetime(df.columns)

print(df.groupby(df.columns.to_period('Q'), axis=1).mean())

   2011Q1  2011Q2
0       1       4
1       7      10

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM