Reputation: 2871
I have a multi-indexed output after pandas crosstab function which is shown below
sports cricket football tennis
nationality
IND 180 18 1
UK 10 30 10
US 5 30 65
From the above, I would like to prepare below df.
Expected output:
nationality cricket football tennis
IND 180 18 1
UK 10 30 10
US 5 30 65
I tried the below code which is giving the wrong data frame.
df_tab.reset_index().iloc[:, 1:]
sports cricket football tennis
IND 180 18 1
UK 10 30 10
US 5 30 65
Upvotes: 1
Views: 741
Reputation: 862741
If need also index and columns names together, first column is index
, all another are columns (but looks same):
df = df_tab.rename_axis(index = None, columns= df_tab.index.name)
print (df)
nationality cricket football tennis
IND 180 18 1
UK 10 30 10
US 5 30 65
print (df.index)
Index(['IND', 'UK', 'US'], dtype='object')
If need print DataFrame without index:
print (df_tab.reset_index().to_string(index=False))
nationality cricket football tennis
IND 180 18 1
UK 10 30 10
US 5 30 65
EDIT: In DataFrame is always necessary index, so if need column from nationality
use:
df = df_tab.reset_index().rename_axis(columns = None)
Upvotes: 1