Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning column names from a list to a table

Tags:

python

pandas

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!

Thanks.

like image 888
Matt Avatar asked Jun 10 '13 07:06

Matt


2 Answers

You can just assign to the columns attribute directly.

>>> 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
like image 196
Jeff Tratner Avatar answered Oct 16 '22 18:10

Jeff Tratner


There is a names argument for read_csv:

names : array-like
      List of column names to use. If file contains no header row, then you
      should explicitly pass header=None

That is, you want to be doing something like:

df = pd.read_csv(fie_name, header=None, names=col_headers_list)
like image 25
Andy Hayden Avatar answered Oct 16 '22 17:10

Andy Hayden