Pandas groupby获得平均一天 - python

我有一个数据框,这是读取csv的结果。它包含日期时间列和与事件相关的数据。我需要使用每20分钟的统计数据计算平均一天,在下面的代码中,我以“平均值”为例。

编辑:
我的数据是观察值。这意味着并非所有存储箱中都有数据。但是在计算平均值时必须考虑这个零计数:mean = count / #days

这段代码有效,但这是要走的路吗?这对我来说看起来很复杂,我想知道我是否真的需要我们的BinID,并且无法按一天中的时间分组。

import pandas as pd

# Create dataframe
data = {'date': pd.date_range('2017-01-01 00:30:00', freq='10min', periods=282),
         'i/o': ['in', 'out'] * 141}
df = pd.DataFrame(data)

# Add ones
df['move'] = 1

# I did try:
# 1)
#    df['time'] = df['date'].dt.time
#    df.groupby(['i/o', pd.Grouper(key='time', freq='20min')])
#    This failed with groupby, so should I use my own bins then???

# 2)
#    Create 20 minutes bins
#    df['binID'] = df['date'].dt.hour*3 + df['date'].dt.minute//20
#    averageDay = df.groupby(['i/o', 'binID']).agg(['count', 'sum', 'mean'])
#
#    Well, bins with zero moves aren't their.
#    So 'mean' can't be used as well as other functions that
#    need the number of observations. Resample and reindex then???

# Resample
df2 = df.groupby(['i/o', pd.Grouper(key='date', freq='20min')]).agg('sum')

# Reindex and reset (for binID and groupby)
levels = [['in', 'out'],
          pd.date_range('2017-01-01 00:00:00', freq='20min', periods=144)]
newIndex = pd.MultiIndex.from_product(levels, names=['i/o', 'date'])
df2 = df2.reindex(newIndex, fill_value=0).reset_index()

# Create 20 minutes bins
df2['binID'] = df2['date'].dt.hour*3 + df2['date'].dt.minute//20

# Average day
averageDay2 = df2.groupby(['i/o', 'binID']).agg(['count', 'sum', 'mean'])
print(averageDay2)

参考方案

IIUC:

In [124]: df.groupby(['i/o',df.date.dt.hour*3 + df.date.dt.minute//20]) \
            .agg(['count','sum','mean'])
Out[124]:
          move
         count sum mean
i/o date
in  0        1   1    1
    1        2   2    1
    2        2   2    1
    3        2   2    1
    4        2   2    1
    5        2   2    1
    6        2   2    1
    7        2   2    1
    8        2   2    1
    9        2   2    1
...        ...  ..  ...
out 62       2   2    1
    63       2   2    1
    64       2   2    1
    65       2   2    1
    66       2   2    1
    67       2   2    1
    68       2   2    1
    69       2   2    1
    70       2   2    1
    71       1   1    1

[144 rows x 3 columns]

python pandas:按行对条件进行分组 - python

我有一个大的pandas数据框,试图从中形成一些行的对。我的df如下所示:object_id increment location event 0 1 d A 0 2 d B 0 3 z C 0 4 g A 0 5 g B 0 6 i C 1 1 k A 1 2 k B ... ... ... ... 对象ID描述特定的对象。增量是每次发生某事(跟踪订单)时…

Python Pandas:按分组分组,平均? - python

我有一个像这样的数据框:cluster org time 1 a 8 1 a 6 2 h 34 1 c 23 2 d 74 3 w 6 我想计算每个集群每个组织的平均时间。预期结果:cluster mean(time) 1 15 ((8+6)/2+23)/2 2 54 (74+34)/2 3 6 我不知道如何在熊猫中做到这一点,有人可以帮忙吗? 参考方案 如…

Python Pandas:在多列上建立布尔索引 - python

尽管至少有关于如何在Python的pandas库中为DataFrame编制索引的two good教程,但我仍然无法在一个以上的列上找到一种优雅的SELECT编码方式。>>> d = pd.DataFrame({'x':[1, 2, 3, 4, 5], 'y':[4, 5, 6, 7, 8]}) >…

Python Pandas:选择索引范围 - python

datas = [['RAC1','CD0287',1.52], ['RAC1','CD0695',2.08], ['RAC1','ADN103-1',2.01], ['RAC3','CD0258',…

Python-Excel导出 - python

我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…