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.
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
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 passheader=None
That is, you want to be doing something like:
df = pd.read_csv(fie_name, header=None, names=col_headers_list)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With