Convert row to column header for Pandas DataFrame,

The data I have to work with is a bit messy.. It has header names inside of its data. How can I choose a row from an existing pandas dataframe and make it (rename it to) a column header?

I want to do something like:

    header = df[df['old_header_name1'] == 'new_header_name1']

    df.columns = header
    In [21]: df = pd.DataFrame([(1,2,3), ('foo','bar','baz'), (4,5,6)])

    In [22]: df
    Out[22]: 
         0    1    2
    0    1    2    3
    1  foo  bar  baz
    2    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]

Drop the 2nd row:

    In [24]: df.reindex(df.index.drop(1))
    Out[24]: 
    1 foo bar baz
    0   1   2   3
    2   4   5   6

From: stackoverflow.com/q/26147180

Back to homepage or read more recommendations: