将列名从列表分配给表

Mat*_*att 8 python pandas

比方说,我有一个100行乘25列的数据表,没有列标题.我有一个25项目列表,我想将其作为列标题分配给数据表(它们已经是正确的顺序).我不知道如何使用pandas有效地做到这一点.任何建议都会很棒!

谢谢.

Jef*_*ner 20

您可以直接分配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
Run Code Online (Sandbox Code Playgroud)

您还可以指定索引来完成类似的操作

>>> df.index = ["row1", "row2", "row3"]
>>> print df
      a  b  c
row1  0  1  2
row2  0  1  2
row3  0  1  2
Run Code Online (Sandbox Code Playgroud)