4

Is it possible to reset columns so they becomes first row of DataFrame. For example,

import pandas as pd

df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
   a  b
0  1  4
1  2  5
2  3  6

Desired ouput,

df2 = df.reset_column() ???
   0  1
0  a  b
1  1  4
2  2  5
3  3  6
1

3 Answers 3

8

Can also chain reset.index

df.T.reset_index().T.reset_index(drop=True)

    0   1
0   a   b
1   1   4
2   2   5
3   3   6
Sign up to request clarification or add additional context in comments.

1 Comment

I didn't want to preserve the column headers, so did: df.reset_index(drop=True).T.reset_index(drop=True).T
7

Use

In [57]: pd.DataFrame(np.vstack([df.columns, df]))
Out[57]:
   0  1
0  a  b
1  1  4
2  2  5
3  3  6

Comments

1

Inserting column names at the first row and resetting the indices.

import pandas as pd

df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})

df.loc[-1] = df.columns
df.index = df.index + 1
df = df.sort_index()
df.columns = [0,1]
df

    0   1
0   a   b
1   1   4
2   2   5
3   3   6

2 Comments

It does overwrite the first row ([1, 4]) with column names.
@taras fixed, look at the updated answer. Thanks for info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.