Convert row to column header for Pandas DataFrame, Convert row to column header for Pandas DataFrame, python python

Convert row to column header for Pandas DataFrame,


In [21]: df = pd.DataFrame([(1,2,3), ('foo','bar','baz'), (4,5,6)])In [22]: dfOut[22]:      0    1    20    1    2    31  foo  bar  baz2    4    5    6

Set the column labels to equal the values in the 2nd row (index location 1):

In [23]: df.columns = df.iloc[1]

If the index has unique labels, you can drop the 2nd row using:

In [24]: df.drop(df.index[1])Out[24]: 1 foo bar baz0   1   2   32   4   5   6

If the index is not unique, you could use:

In [133]: df.iloc[pd.RangeIndex(len(df)).drop(1)]Out[133]: 1 foo bar baz0   1   2   32   4   5   6

Using df.drop(df.index[1]) removes all rows with the same label as the second row. Because non-unique indexes can lead to stumbling blocks (or potential bugs) like this, it's often better to take care that the index is unique (even though Pandas does not require it).


This works (pandas v'0.19.2'):

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


It would be easier to recreate the data frame.This would also interpret the columns types from scratch.

headers = df.iloc[0]new_df  = pd.DataFrame(df.values[1:], columns=headers)