asd
asd

Reputation: 1309

Change columns that contain string and replace rows

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
     

Upvotes: 1

Views: 70

Answers (2)

Dani Mesejo
Dani Mesejo

Reputation: 61910

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

Upvotes: 0

Mayank Porwal
Mayank Porwal

Reputation: 34086

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

Upvotes: 3

Related Questions