Pandas did not return single column data

Dear boss see my simple code
the code did not give me the singel column data after group by

import pandas as pd
data = {
‘Region’: [‘North America’, ‘North America’, ‘North America’, ‘Europe’, ‘Europe’, ‘Asia’, ‘Asia’],
‘Sale’: [76445, 45555, 73356, 54467, 65758, 544456, 75556],
}

df = pd.DataFrame(data)
df2 = df.groupby(‘Region’)[‘Sale’].sum()
test = df2[[‘Region’]]
print(test)

see error

raise KeyError(f"None of [{key}] are in the [{axis_name}]")
KeyError: “None of [Index([‘Region’], dtype=‘object’, name=‘Region’)] are in the [index]”

The group labels (Region) are not in a column but in the index. Try test = df2.index instead.

1 Like

Thank you boss for your reply
but how can I get the all Region name after group by
please send me the code for getting the all Region name after group by
thank you in advance for your help

regard

They are in the index.