1

I have python pandas data frame like this,

           0     1     2     3     4     5     6     7     8
0        121     1     2     3     4     5     6     7     8
1        112     1     2     3     4     5     6     7     8
2        102     1     2     3     4     5     6     7     8
3        121     1     2     3     4     5     6     7     8
4  client_id  var1  var2  var3  var4  var5  var6  var7  var8
5        125     8     7     6     5     4     3     2     1

My column headers are in 5th row, such as client_id and etc..., How to make this row as my df column headers?

Thank you.

1
  • how are you loading this data into the DataFrame. At that step maybe we can add another check for header. Commented Feb 25, 2017 at 10:12

1 Answer 1

4

You can use:

df.columns = df.loc[4]
df = df.drop(4).reset_index(drop=True)
df.columns.name = None
print (df)
  client_id var1 var2 var3 var4 var5 var6 var7 var8
0       121    1    2    3    4    5    6    7    8
1       112    1    2    3    4    5    6    7    8
2       102    1    2    3    4    5    6    7    8
3       121    1    2    3    4    5    6    7    8
4       125    8    7    6    5    4    3    2    1

More dynamic:

idx = df.index[df.iloc[:,0] == 'client_id']
print (idx)
Int64Index([4], dtype='int64')

df.columns = df.loc[idx.item()]
df = df.drop(idx).reset_index(drop=True)
df.columns.name = None
print (df)
  client_id var1 var2 var3 var4 var5 var6 var7 var8
0       121    1    2    3    4    5    6    7    8
1       112    1    2    3    4    5    6    7    8
2       102    1    2    3    4    5    6    7    8
3       121    1    2    3    4    5    6    7    8
4       125    8    7    6    5    4    3    2    1
Sign up to request clarification or add additional context in comments.

3 Comments

command to get 4 ?? if i have bigger data set, I wouldn't know in which line it is, then how to do? please suggest
so all data are numeric, only header row is not numeric?
no, column values can be string, If you can help to get position of client_id, that will do, and making that row as headers. that will do

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.