Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dataframe convert header row to row pandas

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
like image 637
theUnknown Avatar asked Jan 17 '20 08:01

theUnknown


2 Answers

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

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

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
like image 73
jezrael Avatar answered Oct 18 '22 15:10

jezrael


Try using reset_index:

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

For resetting and dropping original columns:

print(df.T.reset_index(drop=True).T)
like image 38
U12-Forward Avatar answered Oct 18 '22 15:10

U12-Forward