Python 使用 orient = 'index' 在 Pandas 数据框 from_dict 中设置列​​名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44882176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:34:23  来源:igfitidea点击:

Set column names in pandas data frame from_dict with orient = 'index'

pythondictionarykey

提问by Euler_Salter

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

我已经看过这个问题:pandas create named columns in dataframe from dict。但是,我的示例略有不同。

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

我有一本字典: 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.

我创建了一个 Pandas dataframe: df = pd.DataFrame.from_dict(my_dict, orient='index'),它是面向行的。但是,在编写时columns = ['one', 'two', 'three']出现错误,如上面的链接所示。

How do I name them?

我如何命名它们?

回答by LangeHaare

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.

应该管用。

回答by Ninjakannon

From version 0.23.0, you can specify a columnsparameter in from_dict:

从版本 0.23.0 开始,您可以在 中指定一个columns参数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'])

回答by Harshini Kanukuntla

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.

将方向从索引更改为列。这对我有用。