Removing dataframe row names in Python Pandas

1.4k Views Asked by At

I have a dataframe like this in Pandas:

# https://www.datasciencemadesimple.com/reshape-long-wide-pandas-python-pivot-function/
import pandas as pd
import numpy as np 

from platform import python_version
print(python_version()) #3.7.7

#Create a DataFrame

d = {'countries':['A','B','C','A','B','C'],
     'continent': ['Europe', 'Asia','Africa', 'Europe', 'Asia','Africa'],
'metrics':['population_in_million','population_in_million','population_in_million',
'gdp_percapita','gdp_percapita','gdp_percapita'],
'values':[100,200,120,2000,7000,15000] }

df = pd.DataFrame(d,columns=['countries','continent','metrics','values'])
df

and I turned it to a wide dataframe using this code:

# https://stackoverflow.com/questions/47178861/pandas-long-to-wide-format-with-multi-index
test_df = pd.DataFrame(df.pivot_table(index=['countries', 'continent'], columns='metrics', values='values'))

test_df = test_df.reset_index() 
test_df

enter image description here

I am looking for a way to remove 'metrics'. Previous answers did not help. My Python version is 3.7.7

1

There are 1 best solutions below

0
On

You should be able to do that by dropping the name of the "columns", i.e.

test_df.columns.name = None

or alternatively, using inbuilt Pandas methods:

test_df.rename_axis(mapper=None, axis=1, inplace=True)

mapper is the value you want to set the name to, axis is 1 because you're looking at the column name, and you can also specify inplace=True if you want to replace the current name with reassignment.