Convertir un objeto Pandas GroupBy a DataFrame
Estoy empezando con datos de entrada como este
df1 = pandas.DataFrame( {
"Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] ,
"City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"] } )
Que cuando se imprime aparece como esto:
City Name
0 Seattle Alice
1 Seattle Bob
2 Portland Mallory
3 Seattle Mallory
4 Seattle Bob
5 Portland Mallory
La agrupación es bastante simple:
g1 = df1.groupby( [ "Name", "City"] ).count()
Y la impresión produce un objeto GroupBy
:
City Name
Name City
Alice Seattle 1 1
Bob Seattle 2 2
Mallory Portland 2 2
Seattle 1 1
Pero lo que quiero eventualmente es otro objeto DataFrame que contenga todas las filas del objeto GroupBy. En otras palabras, quiero obtener el siguiente resultado:
City Name
Name City
Alice Seattle 1 1
Bob Seattle 2 2
Mallory Portland 2 2
Mallory Seattle 1 1
No puedo ver cómo lograr esto en la documentación de los pandas. Cualquier sugerencia sería bienvenida.
8 answers
g1
aquí es un DataFrame. Sin embargo, tiene un índice jerárquico:
In [19]: type(g1)
Out[19]: pandas.core.frame.DataFrame
In [20]: g1.index
Out[20]:
MultiIndex([('Alice', 'Seattle'), ('Bob', 'Seattle'), ('Mallory', 'Portland'),
('Mallory', 'Seattle')], dtype=object)
Tal vez usted quiere algo como esto?
In [21]: g1.add_suffix('_Count').reset_index()
Out[21]:
Name City City_Count Name_Count
0 Alice Seattle 1 1
1 Bob Seattle 2 2
2 Mallory Portland 2 2
3 Mallory Seattle 1 1
O algo así como:
In [36]: DataFrame({'count' : df1.groupby( [ "Name", "City"] ).size()}).reset_index()
Out[36]:
Name City count
0 Alice Seattle 1
1 Bob Seattle 2
2 Mallory Portland 2
3 Mallory Seattle 1
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
2012-04-29 17:50:33
Quiero cambiar ligeramente la respuesta dada por Wes, porque la versión 0.16.2 requiere as_index=False
. Si no lo configura, obtendrá un dataframe vacío.
Las funciones de agregación no devolverán los grupos sobre los que está agregando si se denominan columnas, cuando
as_index=True
, el valor predeterminado. Las columnas agrupadas serán los índices del objeto devuelto.Pasar
as_index=False
devolverá los grupos sobre los que está agregando, si son columnas con nombre.De la Agregación de las funciones que reducir la dimensión de los objetos devueltos, por ejemplo:
mean
,sum
,size
,count
,std
,var
,sem
,describe
,first
,last
,nth
,min
,max
. Esto es lo que sucede cuando haces, por ejemplo,DataFrame.sum()
y recuperas unSeries
.Nth puede actuar como un reductor o un filtro, ver aquí.
import pandas as pd
df1 = pd.DataFrame({"Name":["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"],
"City":["Seattle","Seattle","Portland","Seattle","Seattle","Portland"]})
print df1
#
# City Name
#0 Seattle Alice
#1 Seattle Bob
#2 Portland Mallory
#3 Seattle Mallory
#4 Seattle Bob
#5 Portland Mallory
#
g1 = df1.groupby(["Name", "City"], as_index=False).count()
print g1
#
# City Name
#Name City
#Alice Seattle 1 1
#Bob Seattle 2 2
#Mallory Portland 2 2
# Seattle 1 1
#
EDITAR:
En la versión 0.17.1
y posterior puede usar subset
en count
y reset_index
con el parámetro name
en size
:
print df1.groupby(["Name", "City"], as_index=False ).count()
#IndexError: list index out of range
print df1.groupby(["Name", "City"]).count()
#Empty DataFrame
#Columns: []
#Index: [(Alice, Seattle), (Bob, Seattle), (Mallory, Portland), (Mallory, Seattle)]
print df1.groupby(["Name", "City"])[['Name','City']].count()
# Name City
#Name City
#Alice Seattle 1 1
#Bob Seattle 2 2
#Mallory Portland 2 2
# Seattle 1 1
print df1.groupby(["Name", "City"]).size().reset_index(name='count')
# Name City count
#0 Alice Seattle 1
#1 Bob Seattle 2
#2 Mallory Portland 2
#3 Mallory Seattle 1
La diferencia entre count
y size
es que size
cuenta los valores de NaN mientras que count
no lo hace.
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
2018-08-09 12:28:31
Simplemente, esto debería hacer la tarea:
import pandas as pd
grouped_df = df1.groupby( [ "Name", "City"] )
pd.DataFrame(grouped_df.size().reset_index(name = "Group_Count"))
Aquí, grouped_df.size() muestra el único groupby count, y el método reset_index () restablece el nombre de la columna que desea que sea. Finalmente, se llama a la función pandas Dataframe () para crear el objeto DataFrame.
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
2016-04-30 09:16:35
Encontré que esto funcionó para mí.
import numpy as np
import pandas as pd
df1 = pd.DataFrame({
"Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] ,
"City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"]})
df1['City_count'] = 1
df1['Name_count'] = 1
df1.groupby(['Name', 'City'], as_index=False).count()
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
2016-04-28 22:56:42
Tal vez malinterprete la pregunta, pero si desea convertir el groupby de nuevo a un dataframe puede usar .to_frame(). Quería restablecer el índice cuando hice esto, así que incluí esa parte también.
Código de ejemplo no relacionado con la pregunta
df = df['TIME'].groupby(df['Name']).min()
df = df.to_frame()
df = df.reset_index(level=['Name',"TIME"])
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-03-31 19:45:37
He agregado con datos de Qty wise y almacenar en dataframe
almo_grp_data = pd.DataFrame({'Qty_cnt' :
almo_slt_models_data.groupby( ['orderDate','Item','State Abv']
)['Qty'].sum()}).reset_index()
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
2018-02-01 02:27:45
Debajo de la solución puede ser más simple:
df1.reset_index().groupby( [ "Name", "City"],as_index=False ).count()
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
2018-09-04 05:50:18
Estas soluciones solo funcionaron parcialmente para mí porque estaba haciendo agregaciones múltiples. Aquí hay una salida de muestra de mi agrupado por que quería convertir a un dataframe:
Debido a que quería más que el recuento proporcionado por reset_index(), escribí un método manual para convertir la imagen de arriba en un dataframe. Entiendo que esta no es la forma más pitónica/pandas de hacer esto, ya que es bastante detallada y explícita, pero era todo lo que necesitaba. Básicamente, utilizar el método reset_index () explicado anteriormente para iniciar un dataframe "scaffolding", luego recorrer los emparejamientos de grupo en el dataframe agrupado, recuperar los índices, realizar sus cálculos contra el dataframe no agrupado y establecer el valor en su nuevo dataframe agregado.
df_grouped = df[['Salary Basis', 'Job Title', 'Hourly Rate', 'Male Count', 'Female Count']]
df_grouped = df_grouped.groupby(['Salary Basis', 'Job Title'], as_index=False)
# Grouped gives us the indices we want for each grouping
# We cannot convert a groupedby object back to a dataframe, so we need to do it manually
# Create a new dataframe to work against
df_aggregated = df_grouped.size().to_frame('Total Count').reset_index()
df_aggregated['Male Count'] = 0
df_aggregated['Female Count'] = 0
df_aggregated['Job Rate'] = 0
def manualAggregations(indices_array):
temp_df = df.iloc[indices_array]
return {
'Male Count': temp_df['Male Count'].sum(),
'Female Count': temp_df['Female Count'].sum(),
'Job Rate': temp_df['Hourly Rate'].max()
}
for name, group in df_grouped:
ix = df_grouped.indices[name]
calcDict = manualAggregations(ix)
for key in calcDict:
#Salary Basis, Job Title
columns = list(name)
df_aggregated.loc[(df_aggregated['Salary Basis'] == columns[0]) &
(df_aggregated['Job Title'] == columns[1]), key] = calcDict[key]
Si un diccionario no es lo tuyo, los cálculos podrían aplicarse en línea en el bucle for:
df_aggregated['Male Count'].loc[(df_aggregated['Salary Basis'] == columns[0]) &
(df_aggregated['Job Title'] == columns[1])] = df['Male Count'].iloc[ix].sum()
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
2018-07-13 16:56:41