Python 如何使用 Pandas 将列表转换为行数据框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42202872/
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
How to convert list to row dataframe with Pandas
提问by Federico Gentile
I have a list of items like this:
我有一个这样的项目列表:
A = ['1', 'd', 'p', 'bab', '']
My goal is to convert such list into a dataframe of 1 row and 5 columns. If I type pd.DataFrame(A)
I get 5 rows and 1 column. What should I do in order to get the result I want?
我的目标是将此类列表转换为 1 行 5 列的数据框。如果我输入,pd.DataFrame(A)
我会得到 5 行和 1 列。我该怎么做才能得到我想要的结果?
回答by jezrael
回答by Tom Chapin
This is somewhat peripheral to your particular issue, but I figured I would post it in case it helps someone else out.
这对您的特定问题来说有点外围,但我想我会发布它,以防它帮助其他人。
To convert a list of lists (and give each column a name), just pass the list to the data attribute (along with your desired column names) when instantiating the new dataframe, like so:
要转换列表列表(并为每列指定一个名称),只需在实例化新数据框时将列表传递给数据属性(以及所需的列名),如下所示:
my_python_list = [['foo1', 'bar1'],
['foo2', 'bar2']]
new_df = pd.DataFrame(columns=['my_column_name_1', 'my_column_name_2'], data=my_python_list)
result:
结果:
my_column_name_1 my_column_name_2
0 foo1 bar1
1 foo2 bar2