Equivalente de recuento de pandas (distinto)
Estoy usando pandas como sustituto de bd ya que tengo múltiples bases de datos (oracle, mssql, etc.) y no puedo hacer una secuencia de comandos a un equivalente SQL.
Tengo una tabla cargada en un DataFrame con algunas columnas:
YEARMONTH, CLIENTCODE, SIZE, .... etc etc
En SQL, para contar la cantidad de clientes diferentes por año sería:
SELECT count(distinct CLIENTCODE) FROM table GROUP BY YEARMONTH;
Y el resultado sería
201301 5000
201302 13245
¿Cómo puedo hacer eso en pandas?
150
Author: Andy Hayden, 2013-03-14
3 answers
Creo que esto es lo que quieres:
table.groupby('YEARMONTH').CLIENTCODE.nunique()
Ejemplo:
In [2]: table
Out[2]:
CLIENTCODE YEARMONTH
0 1 201301
1 1 201301
2 2 201301
3 1 201302
4 2 201302
5 2 201302
6 3 201302
In [3]: table.groupby('YEARMONTH').CLIENTCODE.nunique()
Out[3]:
YEARMONTH
201301 2
201302 3
241
Author: Dan Allan,
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-06-10 17:24:37
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-06-10 17:24:37
Aquí hay otro método, muy simple, digamos que su nombre de dataframe es daat
y el nombre de la columna es YEARMONTH
daat.YEARMONTH.value_counts()
37
Author: Enthusiast,
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-07-02 11:16:54
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-07-02 11:16:54
Curiosamente, muy a menudo len(unique())
es un par de veces (3x-15x) más rápido que nunique()
.
31
Author: Roman Kh,
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-12-23 10:55:33
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-12-23 10:55:33