Python Pandas: grupo por en grupo por y promedio?
Tengo un dataframe como este:
cluster org time
1 a 8
1 a 6
2 h 34
1 c 23
2 d 74
3 w 6
Me gustaría calcular el promedio de tiempo por org por clúster.
Resultado esperado:
cluster mean(time)
1 15 ((8+6)/2+23)/2
2 54 (74+34)/2
3 6
No sé cómo hacerlo en Pandas, ¿puede alguien ayudar?
40
2 answers
Si desea tomar primero la media en ['cluster', 'org']
combinación y luego nuevamente tomar la media en cluster
grupos
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
Si no desea valores medios por cluster
solamente, entonces podría
In [58]: df.groupby(['cluster']).mean()
Out[58]:
time
cluster
1 12.333333
2 54.000000
3 6.000000
Podrías groupby
en ['cluster', 'org']
y luego tomar 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
65
Author: Zero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-19 17:16:51
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-19 17:16:51
Simplemente haría esto, lo que literalmente sigue lo que su lógica deseada era:
df.groupby(['org']).mean().groupby(['cluster']).mean()
3
Author: Vincepay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-08 02:23:29
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-08 02:23:29