17

have a df with values

df:

165  156  1    test    greater 56gsa
-------------------------------------
spin 201  2    normal  lesser  12asgs
pine 202  3    fast    greater 5sasgs

required output:

0     1   2     3        4       5
-------------------------------------
165  156  1    test    greater 56gsa
spin 201  2    normal  lesser  12asgs
pine 202  3    fast    greater 5sasgs

3 Answers 3

19

If DataFrame is created from file then header=None parameter is your friend:

df = pd.read_csv(file, header=None)

pandas >= 2.0:

If not then convert column to one row DataFrame and concatenate (append not working anymore) to original data:

df = pd.concat([df.columns.to_frame().T, df])
df.columns = range(len(df.columns))
print (df)
      0    1  2       3        4       5
0   165  156  1    test  greater   56gsa
1  spin  201  2  normal   lesser  12asgs
2  pine  202  3    fast  greater  5sasgs

pandas < 2.0 (original answer):

If not then convert column to one row DataFrame and DataFrame.append to original data:

df = df.columns.to_frame().T.append(df, ignore_index=True)
df.columns = range(len(df.columns))
print (df)
      0    1  2       3        4       5
0   165  156  1    test  greater   56gsa
1  spin  201  2  normal   lesser  12asgs
2  pine  202  3    fast  greater  5sasgs
Sign up to request clarification or add additional context in comments.

Comments

12

Try using reset_index:

print(df.T.reset_index().T)

For resetting and dropping original columns:

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

1 Comment

nice. maybe you want to add .reset_index(drop=True) at the end to reset the new index?
1

Try the code below,

df.loc[len(df)] = df.columns
df.columns = range(len(df.columns))
df

Comments

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.