1

How could I change all columns that have "change_" in the column name? For these columns I want to then conditionally replace rows. Want in general code for a larger dataset

df         change_1   comment   change_2
             onee       number   two
             three      larger   onee
[df[col].mask(df[col]=="onee","one") for col in df.columns if 'change_' in col]

Expected Output:

df         change_1   comment   change_2
             one       number    two
             three      larger   one
     

2 Answers 2

3

Use df.filter to filter out columns and then use df.replace:

In [555]: cols = df.filter(like='change_').columns

In [556]: df[cols] = df[cols].replace('onee', 'one')

In [557]: df
Out[557]: 
  change_1 comment change_2
0      one  number      two
1    three  larger      one
Sign up to request clarification or add additional context in comments.

Comments

0

You could use str.match to find the columns that start with change_, then use replace:

res = df.columns[df.columns.str.match('change_')]
df[res] = df[res].replace({'onee' : 'one'})
print(df)

Output

  change_1 comment change_2
0      one  number      two
1    three  larger      one

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.