2

The python data frame I currently have contains two columns: "EVENT" and "NAME".

EVENT   NAME
A       DEN
B       HAU
C       TOT
D       ABC
E       DEN

I want to implement logic so that my EVENT column is as follows:

EVENT
A_DEN
B
C
D
E_DEN

I want to implement logic that says if "NAME" column contains DEN value then concatenate it to the value in "EVENT" column. Otherwise, leave value as is in "EVENT" column.

I have scoured the internet on how to do this but wasn't able to find anything specific to what I'm trying to accomplish.

1 Answer 1

11

Option 1
You could do this with str.contains/eq to perform the "contains" check, and np.where to conditionally build your result -

df.EVENT = np.where(df.NAME.str.contains('DEN'), df.EVENT + '_' + df.NAME, df.EVENT)

Or,

df.EVENT = np.where(df.NAME.eq('DEN'), df.EVENT + '_' + df.NAME, df.EVENT)

df

   EVENT NAME
0  A_DEN  DEN
1      B  HAU
2      C  TOT
3      D  ABC
4  E_DEN  DEN

Don't forget to import numpy as np.


Option 2
Another method is using pd.Series.mask/pd.Series.where -

df.EVENT = df.EVENT.mask(df.NAME.str.contains('DEN'), df.EVENT + '_' + df.NAME)

Or,

df.EVENT = df.EVENT.where(~df.NAME.str.contains('DEN'), df.EVENT + '_' + df.NAME)

df

   EVENT NAME
0  A_DEN  DEN
1      B  HAU
2      C  TOT
3      D  ABC
4  E_DEN  DEN

Option 3
Yet another option is using loc based indexing with a mask -

m = df.NAME.str.contains('DEN')
df.loc[m, 'EVENT'] += ('_' + df.loc[m, 'NAME'])

df
   EVENT NAME
0  A_DEN  DEN
1      B  HAU
2      C  TOT
3      D  ABC
4  E_DEN  DEN
Sign up to request clarification or add additional context in comments.

12 Comments

I was just going to post the one with np.where :)
@Vaishali np.where is usually the bread and butter for many pandas problems... easy to implement too, one of my favourite numpy functions :-)
@cᴏʟᴅsᴘᴇᴇᴅ Is it safe to use pd.np.where? or would importing np and np.where be more future proof?
@AntonvBR I think np.where would be safer, I use pd.np so op doesn't need to import numpy as np explicitly. Will edit.
it worked! I removed the extra set of parenthesis I added in ... thank you so much for your detailed response!
|

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.