0

Q1) Is there any way to set row to column-row in DataFrame?

     (DF)                                      (DF)
   A  B  C  D                                a  b  c  d
0  a  b  c  d       pandas function       0  4  5  3  6
1  4  5  3  6 ==========================> 1  3  2  5  3
2  3  2  5  3  0-idx row to columns-row   2  4  7  9  0
3  4  7  9  0

Q2) How to get DataFrame from Excel file with setting any index row to column_row?

(EXCEL or CSV)                                 (DF)
   A  B  C  D                                a  b  c  d
0  a  b  c  d       pd.read_excel()       0  4  5  3  6
1  4  5  3  6 ==========================> 1  3  2  5  3
2  3  2  5  3  0-idx row to columns-row   2  4  7  9  0
3  4  7  9  0
khg
  • 15
  • 5
  • 1
    How to set row to header: https://stackoverflow.com/questions/26147180/convert-row-to-column-header-for-pandas-dataframe for the second when reading specify ```header=true``` – FloLie Jul 16 '20 at 07:16
  • thanks, i saw your link and i could solve Q2 by adding parameter 'header'. – khg Jul 16 '20 at 08:38

2 Answers2

0

This would do the job:

new_header = df.iloc[0] #first_row
df = df[1:] #remaining_dataframe
df.columns = new_header
Raj Srujan Jalem
  • 613
  • 5
  • 17
0

You can try it:

import pandas as pd
data={"A":['a',4,3,4],"B":['b',5,2,7],"C":['c',3,5,9],"D":['d',6,3,0]}

df=pd.DataFrame(data)

#define the column name from line index 0
df.columns=df.iloc[0].tolist()
#remove the line index 0
df = df.drop(0)

result:

   a  b  c  d
1  4  5  3  6
2  3  2  5  3
3  4  7  9  0
Renaud
  • 2,709
  • 2
  • 9
  • 24