0

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.