如何获得日期时间序列的随机数的平均值和总和?

问题描述 投票:1回答:1

我为2016年的所有工作日创建了一个系列,然后为每个日期分配了随机数:创建了2016年的日期时间索引:

df= pd.bdate_range('2016-01-01', '2016-12-31')

产量

  DatetimeIndex(['2016-01-01', '2016-01-04', '2016-01-05', '2016-01-06',
           '2016-01-07', '2016-01-08', '2016-01-11', '2016-01-12',
           '2016-01-13', '2016-01-14',
           ...
           '2016-12-19', '2016-12-20', '2016-12-21', '2016-12-22',
           '2016-12-23', '2016-12-26', '2016-12-27', '2016-12-28',
           '2016-12-29', '2016-12-30'],
          dtype='datetime64[ns]', length=261, freq='B')

为每列创建索引:

    s = pd.Series(np.random.randn(len(df)), index=df)

  output
2016-01-01    0.430445
2016-01-04   -0.378483
2016-01-05    0.410059
2016-01-06    2.276409
2016-01-07    1.102603
2016-01-08   -0.339722
2016-01-11    0.542110
2016-01-12   -0.898154
 ......
 2016-12-28   -0.952172
 2016-12-29   -1.522073
 2016-12-30   -1.065957

我想获得为我周二的每个值创建的索引总和,并且我想获得每个月的索引的平均值。

python python-3.x pandas numpy
1个回答
2
投票

Problem 1: Sum of tuesday values

使用dayofweek,索引dayofweek == 1(代表星期二)

s[s.index.dayofweek == 1].sum()

# Output:
2.1416224135016124

Problem 2: Mean by month

使用groupbypd.Grouper(freq='m')

s.groupby(pd.Grouper(freq='m')).mean()

# Output:
2016-01-31    0.072559
2016-02-29    0.009706
2016-03-31    0.118553
2016-04-30   -0.228017
2016-05-31    0.132211
2016-06-30   -0.188015
2016-07-31    0.008239
2016-08-31   -0.181972
2016-09-30    0.554330
2016-10-31   -0.293271
2016-11-30   -0.092587
2016-12-31   -0.268706
Freq: M, dtype: float64
© www.soinside.com 2019 - 2024. All rights reserved.