JamesHudson81
JamesHudson81

Reputation: 2273

replace values from a column into another if it contains 2 substrings

I have a df like this:

            xx    yy
AAsdsd_ss   3     2
AAassa_ss   3     1
CC          4     7 
DD          7     6

I would like that if the index str.contain AA and _ss to substitute the values of column yy into xx to generate the following output:

            xx    
AAsdsd_ss   2     
AAassa_ss   1         
CC          4      
DD          7    

How could I achieve this?

Upvotes: 0

Views: 19

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

IIUC:

df.loc[df.index.to_series().str.match('^AA.*_ss$'), 'xx'] = df['yy'] 

Output:

           xx  yy
AAsdsd_ss   2   2
AAassa_ss   1   1
CC          4   7
DD          7   6

Note: the code matches AA at beginning and _ss at the end. If you simply want them anywhere, in any order:

s = df.index.to_series()
df.loc[s.str.contains('AA') & s.str.contains('_ss'), 'xx'] = df['yy']

Upvotes: 1

Related Questions