Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to take index list from groupby dataframe pandas

enter image description here

i have this result from group by my df, how can i take a list name of City from this result df? i found this solving problem but i dont know how this for loop works:

enter image description here

i think result is 2 part, index list and a new dataframe, so when input city,df in groupby df. it will return first list is city and the other in df. Is it true? but the type of df when i print(type(df)) is list, i thought it containt all the list except index list i had push into city. but when i try for loop with city,df,df1,df2,.. error appear :(

like image 411
robocon20x Avatar asked Sep 18 '25 16:09

robocon20x


2 Answers

i have this result from group by my df, how can i take a list name of City from this result df?

result = all_data.groupby('City').sum()

result is Series, where City is converted to index, so simpliest is:

cities = result.index

For plotting it is more easier if use DataFrame.plot.bar, by default index is plotting in axis=x:

result.plot.bar()

You can rewrite your list comprehension for loop by groupby object, so here city is grouped column unique values and df is group:

for city, df  in all_data.groupby('City'):
    print (city)
    print (df)

So if extract city get unique values by City column, which is converted to index after aggregate sum.

cities = [city for city, df  in all_data.groupby('City')]
like image 182
jezrael Avatar answered Sep 21 '25 06:09

jezrael


Try converting it into a dataframe first and then use df for your calculations:

df = pd.DataFrame(all_data.groupby(['City']))

like image 26
cosmo nova Avatar answered Sep 21 '25 05:09

cosmo nova