Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming columns of a pandas dataframe without column names [duplicate]

Tags:

python

pandas

I'm trying to name the columns of my new dataframe after the dataframe.from_dict operation.

Simply using pandas.dataframe.from_dict function:

df = pd.DataFrame.from_dict(my_dict,orient='index')

yields the dataframe without column headers.

data=pd.DataFrame.from_dict(my_dict,orient='index).rename(columns = {'name','number'}) 

This yields nothing an error : TypeError: 'set' object is not callable.

Does anybody have a clue?

like image 608
tlhy Avatar asked Nov 07 '22 19:11

tlhy


1 Answers

If you want the index as the keys in your dict, you don't need to rename it.

df = pd.DataFrame.from_dict(dicts, orient = 'index') #index is name

df.columns = (['number']) #non-index column is number

df.index.name = 'name'

Or instead of changing the index name you can make a new column:

df = df.reset_index() #named column becomes index, index becomes ordered sequence

df['name'] = df['index'] #new column with names

del df['index'] #delete old column
like image 186
snapcrack Avatar answered Nov 15 '22 05:11

snapcrack