如何在熊猫时间序列中按日期对日期进行分组?

时间:2019-11-03 06:48:49

标签: time-series pandas-groupby

我有AAPL的以下数据:

    High    Low Open    Close   Volume  Adj Close
Date                        
1987-12-31  1.535714    1.495536    1.517857    1.500000    29400000.0  1.200883
1988-01-04  1.598214    1.508929    1.526786    1.598214    82600000.0  1.279513
1988-01-05  1.651786    1.580357    1.642857    1.593750    77280000.0  1.275938
1988-01-06  1.607143    1.562500    1.607143    1.562500    67200000.0  1.250920
1988-01-07  1.598214    1.517857    1.553571    1.589286    53200000.0  1.272364
... ... ... ... ... ... ...
2007-12-24  28.475714   27.827143   27.861429   28.400000   120050700.0 24.785059
2007-12-26  28.708570   28.117144   28.430000   28.421429   175933100.0 24.803761
2007-12-27  28.994286   28.257143   28.421429   28.367144   198881900.0 24.756376
2007-12-28  28.794285   28.125713   28.655714   28.547142   174911800.0 24.913471
2007-12-31  28.642857   28.250000   28.500000   28.297142   134833300.0 24.695290
5044 rows × 6 columns

我想做的是添加另一列,该列将按月和年对所有数据进行分组。这样,我可以在几个月或几年内进行手术。日期已在日期时间中。

1 个答案:

答案 0 :(得分:0)

您可以提取年份和月份,并将它们放在“年”和“月”两列中,

df['year'] = df['Date'].dt.year
df['month'] = df['Date'].dt.month

如果您只希望使用“ year_and_month”列,则可以使用:

df['year_and_month'] = df['Date'].dt.year.astype('str') + '-' + df['Date'].dt.month.astype('str')