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 🙁

Answer

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')]