Python Pandas : group by 和 average?
Python Pandas : group by in group by and average?
我有一个这样的数据框:
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
我不知道如何在 Pandas 中执行此操作,有人可以帮忙吗?
如果你想先对['cluster', 'org']
的组合取均值,然后对cluster
组取均值,你可以使用:
In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean()
.groupby('cluster')['time'].mean())
Out[59]:
cluster
1 15
2 54
3 6
Name: time, dtype: int64
如果你只想要 cluster
组的平均值,那么你可以使用:
In [58]: df.groupby(['cluster']).mean()
Out[58]:
time
cluster
1 12.333333
2 54.000000
3 6.000000
您也可以在 ['cluster', 'org']
上使用 groupby
,然后使用 mean()
:
In [57]: df.groupby(['cluster', 'org']).mean()
Out[57]:
time
cluster org
1 a 438886
c 23
2 d 9874
h 34
3 w 6
我会简单地这样做,它确实遵循您想要的逻辑:
df.groupby(['org']).mean().groupby(['cluster']).mean()
我有一个这样的数据框:
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
我不知道如何在 Pandas 中执行此操作,有人可以帮忙吗?
如果你想先对['cluster', 'org']
的组合取均值,然后对cluster
组取均值,你可以使用:
In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean()
.groupby('cluster')['time'].mean())
Out[59]:
cluster
1 15
2 54
3 6
Name: time, dtype: int64
如果你只想要 cluster
组的平均值,那么你可以使用:
In [58]: df.groupby(['cluster']).mean()
Out[58]:
time
cluster
1 12.333333
2 54.000000
3 6.000000
您也可以在 ['cluster', 'org']
上使用 groupby
,然后使用 mean()
:
In [57]: df.groupby(['cluster', 'org']).mean()
Out[57]:
time
cluster org
1 a 438886
c 23
2 d 9874
h 34
3 w 6
我会简单地这样做,它确实遵循您想要的逻辑:
df.groupby(['org']).mean().groupby(['cluster']).mean()