Set column names in pandas data frame from_dict wi

2020-03-01 06:18发布

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?

3条回答
够拽才男人
2楼-- · 2020-03-01 07:02
my_dict = {'key1' : [1,2,3], 'key2' : [4,5,6], 'key3' :[7,8,9]}
df = pd.DataFrame.from_dict(my_dict, orient='cloumns')
df.columns = ['one', 'two', 'three']

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

查看更多
淡お忘
3楼-- · 2020-03-01 07:06

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'])
查看更多
We Are One
4楼-- · 2020-03-01 07:20

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.

查看更多
登录 后发表回答