17

I looked already at this question: pandas create named columns in dataframe from dict. However, my example is slightly different.

I have a dictionary: my_dict = {'key1' : [1,2,3], 'key2' : [4,5,6], 'key3' :[7,8,9]}

And I created a pandas dataframe: df = pd.DataFrame.from_dict(my_dict, orient='index'), which is row oriented. However, when writing columns = ['one', 'two', 'three'] I get an error, as in the link above.

How do I name them?

Ninjakannon
  • 3,283
  • 5
  • 42
  • 65
Euler_Salter
  • 2,465
  • 2
  • 22
  • 48
  • 3
    The way to solve it is answered in your linked question (with one less column). Just look at the accepted answer: `pd.DataFrame(list(my_dict.iteritems()),columns=['business_id','business_code'])`, so in your case `pd.DataFrame(list(my_dict.iteritems()),columns=['one','two','three'])` (credit to [Andy Hayden](https://stackoverflow.com/users/1240268/andy-hayden)) – C.Fe. Jul 03 '17 at 09:41

3 Answers3

27

Is there a reason you can't set the column names on the next line?

my_dict = {'key1' : [1,2,3], 'key2' : [4,5,6], 'key3' :[7,8,9]}
df = pd.DataFrame.from_dict(my_dict, orient='index')
df.columns = ['one', 'two', 'three']

Should work.

LangeHaare
  • 2,010
  • 1
  • 13
  • 23
6

From version 0.23.0, you can specify a columns parameter in from_dict:

my_dict = {'key1': [1, 2, 3], 'key2': [4, 5, 6], 'key3': [7, 8, 9]}
df = pd.DataFrame.from_dict(my_dict, orient='index', columns=['one', 'two', 'three'])
Ninjakannon
  • 3,283
  • 5
  • 42
  • 65
0
my_dict = {'key1' : [1,2,3], 'key2' : [4,5,6], 'key3' :[7,8,9]}
df = pd.DataFrame.from_dict(my_dict, orient='columns')
df.columns = ['one', 'two', 'three']

Changed orient from index to columns. This worked for me.

Ralph Willgoss
  • 9,622
  • 4
  • 64
  • 65