Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas Replacing Header with Top Row

People also ask

How do I change the header row in pandas?

You can replace the header with the first row of the dataframe by using df. columns = df. iloc[0]. You can use the below code snippet to replace the header with the first row of the pandas dataframe.

How do I get rid of the pandas header?

In order to export pandas DataFrame to CSV without index (no row indices) use param index=False and to ignore/remove header use header=False param on to_csv() method.


new_header = df.iloc[0] #grab the first row for the header
df = df[1:] #take the data less the header row
df.columns = new_header #set the header row as the df header

The dataframe can be changed by just doing

df.columns = df.iloc[0]
df = df[1:]

Then

df.to_csv(path, index=False) 

Should do the trick.


If you want a one-liner, you can do:

df.rename(columns=df.iloc[0]).drop(df.index[0])

@ostrokach answer is best. Most likely you would want to keep that throughout any references to the dataframe, thus would benefit from inplace = True.
df.rename(columns=df.iloc[0], inplace = True) df.drop([0], inplace = True)


Another one-liner using Python swapping:

df, df.columns = df[1:] , df.iloc[0]

This won't reset the index

Although, the opposite won't work as expected df.columns, df = df.iloc[0], df[1:]


Here's a simple trick that defines column indices "in place". Because set_index sets row indices in place, we can do the same thing for columns by transposing the data frame, setting the index, and transposing it back:

df = df.T.set_index(0).T

Note you may have to change the 0 in set_index(0) if your rows have a different index already.