arkadiy
arkadiy

Reputation: 766

For loop for dropping a string pattern from a column name

I am attempting to drop '_Adj' from a column name, in a 'df_merged' data frame if (1) a column name contains 'eTIV' or "eTIV1'.

for col in df_merged.columns:
    if 'eTIV1' in col or 'eTIV' in col:
        df_merged.columns.str.replace('_Adj', '')

This code seems to be producing the following error:

KeyError: '[] not found in axis'

Upvotes: 1

Views: 27

Answers (1)

rahlf23
rahlf23

Reputation: 9019

Here are two options:

Option 1

df_merged.columns = [col.replace('_Adj','') if 'eTIV' in col else col for col in list(df_merged.columns)]

Option 2

df_merged = df_merged.rename(columns={col: col.replace('_Adj','') if 'eTIV' in col else col for col in df_merged.columns})

Upvotes: 1

Related Questions