Efficient ways of assigning value based on conditional in Pandas?

Viewed 35

The objective is to assign a value to the column EXPECTED T. The value to be assigned is C1 S + C2 B if there is EM in column C2 B, else the value is image of the value at C2 B.

To realise the objective, the following code is propose

data = {'C1 S': ['AB','AB','CD','CD','CD'],
        'C2 B': ['EM','EM','EM','F','F'],
        'EXPECTED_OUTPUT': ['AB EM','EB EM', 'CD EM','F','F']}
df = pd.DataFrame(data)
df['EXPECTED T']=df['C1 S']+' '+ df['C2 B']
mask = df ['C2 B'].str.contains ( r'EM', na=True )
df.loc [~mask, 'EXPECTED T'] = df.loc [~mask, 'C2 B']

But, I wonder if there is more Pythonic of achieving similar result then the above code?

1 Answers

Use numpy.where or Series.mask, also is possible use here Series.str.cat:

mask = df['C2 B'].str.contains ( r'EM', na=True )
df['EXPECTED T'] = np.where(mask, df['C1 S']+' '+ df['C2 B'], df['C2 B'])

#alternative
df['EXPECTED T'] = np.where(mask, df['C1 S'].str.cat( df['C2 B'], sep=' '), df['C2 B'])
print (df)
  C1 S C2 B EXPECTED_OUTPUT EXPECTED T
0   AB   EM           AB EM      AB EM
1   AB   EM           EB EM      AB EM
2   CD   EM           CD EM      CD EM
3   CD    F               F          F
4   CD    F               F          F

Or:

mask = df['C2 B'].str.contains ( r'EM', na=True )
df['EXPECTED T'] = df['C2 B'].mask(mask, df['C1 S']+' '+ df['C2 B'])
Related