5

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?

tlhy
  • 125
  • 1
  • 2
  • 8
  • You'd want `df.columns = ['name','number']` – cs95 Jul 14 '17 at 03:44
  • I think you can check [this](https://stackoverflow.com/questions/11346283/renaming-columns-in-pandas?rq=1) - all possible renaming of columns. And it seems it is dupe. – jezrael Jul 14 '17 at 03:54
  • Thanks COLDSPEED and jezrael! @COLDSPEED - the method doesn't work unfortunately - the printed message is "ValueError: Length Mismatch: Expected axis has 1 elements, new values have 2 elements". I think it's possible that the df.from_dict function causes the key of the dictionary to be the index of the dataframe (because it gets pasted in the first column). jezrael i've read that post and the methods used didn't work – tlhy Jul 17 '17 at 01:07

2 Answers2

1

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
snapcrack
  • 1,761
  • 3
  • 20
  • 40
0

You can probably do something like this by implicitly referring the columns names and then set new names.

data = (  
  pd.DataFrame.from_dict(my_dict,orient='index')
  .rename(columns=dict(zip(df.columns,['name','number'])))
)
Allen Qin
  • 19,507
  • 8
  • 51
  • 67