Marvin Castillo
Marvin Castillo

Reputation: 13

How can I add a whole row as a column name in Pandas?

I have a data set as follows:

sureste_1 sureste_2 ... sureste_136

1 CO NO NOX O3 ...

So what I want to do is to drag the whole row into the column names, so it says:

sureste_1_CO sureste_2_NO sureste_3_NOX ... and so on.

Makes sense?

Upvotes: 1

Views: 53

Answers (1)

jezrael
jezrael

Reputation: 863741

For append values to columns names by first row use:

print (df)
  sureste_1 sureste_2 sureste_3 sureste_136
1        CO        NO       NOX          O3

#row with label 1
df.columns = df.columns + '_' + df.loc[1]
#first row
#df.columns = df.columns + '_' + df.iloc[0]
print (df)
  sureste_1_CO sureste_2_NO sureste_3_NOX sureste_136_O3
1           CO           NO           NOX             O3

Another idea with list comprehension and f-strings:

df.columns = [f'{k}_{v}' for k, v in df.loc[1].items()]
print (df)
  sureste_1_CO sureste_2_NO sureste_3_NOX sureste_136_O3
1           CO           NO           NOX             O3

Upvotes: 1

Related Questions