GVKun编程网logo

Python Pandas:按分组分组,平均?(python pandas 分组)

8

在本文中,我们将给您介绍关于PythonPandas:按分组分组,平均?的详细内容,并且为您解答pythonpandas分组的相关问题,此外,我们还将为您提供关于Pandas/Python–按时间段分

在本文中,我们将给您介绍关于Python Pandas:按分组分组,平均?的详细内容,并且为您解答python pandas 分组的相关问题,此外,我们还将为您提供关于Pandas / Python – 按时间段分组数据、pandas数据框:按两列分组,然后对另一列取平均值、Pandas获得分组平均、Pandas:按列A分组,并从其他列中列出元组?的知识。

本文目录一览:

Python Pandas:按分组分组,平均?(python pandas 分组)

Python Pandas:按分组分组,平均?(python pandas 分组)

我有一个这样的数据框:

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)/22       54   (74+34)/23       6

我不知道如何在熊猫中做到这一点,有人可以帮忙吗?

答案1

小编典典

如果你想先对[''cluster'', ''org'']组合取平均值,然后再对cluster组取平均值

In [59]: (df.groupby([''cluster'', ''org''], as_index=False).mean()            .groupby(''cluster'')[''time''].mean())Out[59]:cluster1          152          543           6Name: time, dtype: int64

如果你cluster不仅仅希望价值观,那么你可以

In [58]: df.groupby([''cluster'']).mean()Out[58]:              timecluster1        12.3333332        54.0000003         6.000000

你可以groupby上[''cluster'', ''org'']再取mean()

In [57]: df.groupby([''cluster'', ''org'']).mean()Out[57]:               timecluster org1       a    438886        c        232       d      9874        h        343       w         6

Pandas / Python – 按时间段分组数据

Pandas / Python – 按时间段分组数据

我有一些财务数据,并希望只获得特定时间段(小时,天,月……)的最后一笔交易.

例:

>>df
      time  price_BRL     qt              time_dt
1312001297      23.49   1.00  2011-07-30 04:48:17
1312049148      23.40   1.00  2011-07-30 18:05:48
1312121523      23.49   2.00  2011-07-31 14:12:03
1312121523      23.50   6.50  2011-07-31 14:12:03
1312177622      23.40   2.00  2011-08-01 05:47:02
1312206416      23.25   1.00  2011-08-01 13:46:56
1312637929      18.95   1.50  2011-08-06 13:38:49
1312637929      18.95   4.00  2011-08-06 13:38:49
1312817114       0.80   0.01  2011-08-08 15:25:14
1312818289       0.10   0.01  2011-08-08 15:44:49
1312819795       6.00   0.09  2011-08-08 16:09:55
1312847064      16.00   0.86  2011-08-08 23:44:24
1312849282      16.00   6.14  2011-08-09 00:21:22
1312898146      19.90   1.00  2011-08-09 13:55:46
1312915666       6.00   0.01  2011-08-09 18:47:46
1312934897      19.90   1.00  2011-08-10 00:08:17
>>filter_by_last_day(df)
      time  price_BRL     qt              time_dt
1312049148      23.40   1.00  2011-07-30 18:05:48
1312121523      23.50   6.50  2011-07-31 14:12:03
1312206416      23.25   1.00  2011-08-01 13:46:56
1312637929      18.95   4.00  2011-08-06 13:38:49
1312847064      16.00   0.86  2011-08-08 23:44:24
1312915666       6.00   0.01  2011-08-09 18:47:46
1312934897      19.90   1.00  2011-08-10 00:08:17

我正在考虑使用groupby()并获得当天的平均值()这个解决方案也可以解决我的问题,但不完全正确)但不知道如何选择df.groupby这样的日子(‘time.day ‘).持续()

最佳答案
您可以在dt.date之前使用groupby并在last之前聚合:

#if necessery convert to datetime
df.time_dt = pd.to_datetime(df.time_dt)

df = df.groupby(df.time_dt.dt.date).last().reset_index(drop=True)
print (df)
         time  price_BRL    qt             time_dt
0  1312049148      23.40  1.00 2011-07-30 18:05:48
1  1312121523      23.50  6.50 2011-07-31 14:12:03
2  1312206416      23.25  1.00 2011-08-01 13:46:56
3  1312637929      18.95  4.00 2011-08-06 13:38:49
4  1312847064      16.00  0.86 2011-08-08 23:44:24
5  1312915666       6.00  0.01 2011-08-09 18:47:46
6  1312934897      19.90  1.00 2011-08-10 00:08:17

谢谢MaxU的另一个解决方案 – 为返回DataFrame添加参数as_index = False:

df = df.groupby(df.time_dt.dt.date,as_index=False).last()
print (df)
         time  price_BRL    qt             time_dt
0  1312049148      23.40  1.00 2011-07-30 18:05:48
1  1312121523      23.50  6.50 2011-07-31 14:12:03
2  1312206416      23.25  1.00 2011-08-01 13:46:56
3  1312637929      18.95  4.00 2011-08-06 13:38:49
4  1312847064      16.00  0.86 2011-08-08 23:44:24
5  1312915666       6.00  0.01 2011-08-09 18:47:46
6  1312934897      19.90  1.00 2011-08-10 00:08:17

使用resample的解决方案,但必须在dropna之前删除NaN行:

df = df.resample('d',on='time_dt').last().dropna(how='all').reset_index(drop=True)
#cast column time to int
df.time = df.time.astype(int)
print (df)
         time  price_BRL    qt             time_dt
0  1312049148      23.40  1.00 2011-07-30 18:05:48
1  1312121523      23.50  6.50 2011-07-31 14:12:03
2  1312206416      23.25  1.00 2011-08-01 13:46:56
3  1312637929      18.95  4.00 2011-08-06 13:38:49
4  1312847064      16.00  0.86 2011-08-08 23:44:24
5  1312915666       6.00  0.01 2011-08-09 18:47:46
6  1312934897      19.90  1.00 2011-08-10 00:08:17

你也可以使用dt.month

df = df.groupby(df.time_dt.dt.month).last().reset_index(drop=True)
print (df)
         time  price_BRL   qt             time_dt
0  1312121523       23.5  6.5 2011-07-31 14:12:03
1  1312934897       19.9  1.0 2011-08-10 00:08:17

有几个小时它有点复杂,如果需要groupby按日期和小时一起,解决方案是用astype将分钟和秒数替换为0:

hours = df.time_dt.values.astype('

pandas数据框:按两列分组,然后对另一列取平均值

pandas数据框:按两列分组,然后对另一列取平均值

假设我有一个具有以下值的数据框:

df:
col1    col2    value
1       2       3
1       2       1
2       3       1

我想首先根据前两列(col1和col2)对数据框进行分组,然后对第三列的值(值)进行平均。因此,所需的输出将如下所示:

col1    col2    avg-value
1       2       2
2       3       1

我正在使用以下代码:

columns = ['col1','col2','avg']
df = pd.DataFrame(columns=columns)
df.loc[0] = [1,2,3]
df.loc[1] = [1,3,3]
print(df[['col1','avg']].groupby('col1','col2').mean())

出现以下错误:

ValueError: No axis named col2 for object type <class 'pandas.core.frame.DataFrame'>

任何帮助将非常感激。

Pandas获得分组平均

Pandas获得分组平均

我试图找到每个user_id的平均每月费用,但是我只能获取每个用户的平均费用或每个用户的每月费用。

因为我按用户和月份分组,否则除非我将groupby输出转换为其他值,否则无法获取第二个groupby(月份)的平均值。

这是我的df:

     df = { 'id' : pd.Series([1,1,2,2]),'cost' : pd.Series([10,20,30,40,50,60,70,80]),'mth': pd.Series([3,3,4,5,5])}

   cost  id  mth
0    10   1    3
1    20   1    3
2    30   1    4
3    40   1    5
4    50   2    3
5    60   2    4
6    70   2    4
7    80   2    5

我可以获得每月的总和,但我希望每个user_id的月份平均值。

df.groupby(['id','mth'])['cost'].sum()

id  mth
1   3       30
    4       30
    5       40
2   3       50
    4      130
    5       80

我想要这样的事情:

id average_monthly
1 (30+30+40)/3
2 (50+130+80)/3

Pandas:按列A分组,并从其他列中列出元组?

Pandas:按列A分组,并从其他列中列出元组?

我想将用户交易汇总到熊猫列表中。我不知道如何制作一个包含多个字段的列表。例如,

df = pd.DataFrame({''user'':[1,1,2,2,3],                    ''time'':[20,10,11,18, 15],                    ''amount'':[10.99, 4.99, 2.99, 1.99, 10.99]})

看起来像

    amount  time  user0   10.99    20     11    4.99    10     12    2.99    11     23    1.99    18     24   10.99    15     3

如果我做

print(df.groupby(''user'')[''time''].apply(list))

我懂了

user1    [20, 10]2    [11, 18]3        [15]

但是如果我这样做

df.groupby(''user'')[[''time'', ''amount'']].apply(list)

我懂了

user1    [time, amount]2    [time, amount]3    [time, amount]

多亏了下面的答案,我才知道我可以做到这一点

df.groupby(''user'').agg(lambda x: x.tolist()))

要得到

             amount      timeuser                         1     [10.99, 4.99]  [20, 10]2      [2.99, 1.99]  [11, 18]3           [10.99]      [15]

但是我要按照相同的顺序对时间和金额进行排序-这样我才能按顺序处理每个用户的交易。

我一直在寻找一种产生这种方式的方法:

             amount-time-tupleuser                         1     [(20, 10.99), (10, 4.99)]2     [(11,  2.99), (18, 1.99)]3     [(15, 10.99)]

但是也许有一种方法可以在不“纠缠”两列的情况下进行排序?

答案1

小编典典

apply(list) 我会考虑序列索引而不是值。我认为您正在寻找

df.groupby(''user'')[[''time'', ''amount'']].apply(lambda x: x.values.tolist())用户1 [[23.0,2.99],[50.0,1.99]]2 [[12.0,1.99]]

关于Python Pandas:按分组分组,平均?python pandas 分组的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Pandas / Python – 按时间段分组数据、pandas数据框:按两列分组,然后对另一列取平均值、Pandas获得分组平均、Pandas:按列A分组,并从其他列中列出元组?等相关知识的信息别忘了在本站进行查找喔。

本文标签: