Python 将列表中的列名分配给表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17018638/
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
Assigning column names from a list to a table
提问by Matt
I have, say, a 100 row by 25 column data table with no column headers. I have a 25-item list that I would like to assign as the column headers to the data table (they're in the right order already). I don't know how to do this efficiently using pandas. Any suggestions would be great!
比如说,我有一个 100 行 x 25 列的数据表,没有列标题。我有一个包含 25 个项目的列表,我想将它分配为数据表的列标题(它们的顺序已经正确)。我不知道如何使用熊猫有效地做到这一点。任何建议都会很棒!
Thanks.
谢谢。
采纳答案by Jeff Tratner
You can just assign to the columnsattribute directly.
您可以直接分配给columns属性。
>>> import pandas
>>> # create three rows of [0, 1, 2]
>>> df = pandas.DataFrame([range(3), range(3), range(3)])
>>> print df
0 1 2
0 0 1 2
1 0 1 2
2 0 1 2
>>> my_columns = ["a", "b", "c"]
>>> df.columns = my_columns
>>> print df
a b c
0 0 1 2
1 0 1 2
2 0 1 2
You can also assign to index to accomplish something similar
您还可以分配给索引来完成类似的事情
>>> df.index = ["row1", "row2", "row3"]
>>> print df
a b c
row1 0 1 2
row2 0 1 2
row3 0 1 2
回答by Andy Hayden
There is a names argument for read_csv:
有一个名称参数read_csv:
names: array-like
List of column names to use. If file contains no header row, then you
should explicitly passheader=None
names: 类数组
要使用的列名列表。如果文件不包含标题行,那么您
应该显式传递header=None
That is, you want to be doing something like:
也就是说,您想要执行以下操作:
df = pd.read_csv(fie_name, header=None, names=col_headers_list)

