question.it
question.it

Reputation: 2968

Replace Dataframe column name

I have dataframe with below columns:

'TERRITORY', 'FIELD OF STUDY', 'SELECT YEAR T (ACADEMIC YEAR = T-1  OR  T)', 'VALUE'

I want to replace "YEAR" if dataframe column name contains "SELECT YEAR". How to do that?

Upvotes: 0

Views: 178

Answers (1)

jezrael
jezrael

Reputation: 862511

One simple solution is use list comprehension:

df.columns = ["YEAR" if "SELECT YEAR" in x else x for x in df.columns]

Pandas solution:

df.columns = df.columns.where(~df.columns.str.contains('SELECT YEAR'), 'YEAR')

Only be careful if multiple values was setting, then problem with selecting, because:

print (df['YEAR'])

return all columns YEAR.

Sample:

c = ['SELECT YEAR  d', 'FIELD OF STUDY', 'SELECT YEAR T (ACADEMIC YEAR = T-1  OR  T)', 'VALUE']
df = pd.DataFrame(0, columns=c, index=[1,2])

df.columns = ["YEAR" if "SELECT YEAR" in x else x for x in df.columns]
print (df)
   YEAR  FIELD OF STUDY  YEAR  VALUE
1     0               0     0      0
2     0               0     0      0

print (df['YEAR'])
   YEAR  YEAR
1     0     0
2     0     0

Upvotes: 1

Related Questions