Sunil Raperia
Sunil Raperia

Reputation: 125

Create new column on basis of another column in Pandas

I have a column in Dataframe by the name STATUS, which contains value "AMEND ORDER" or it is empty. I need to create a FLAG on the basis of that column, if it values contains AMEND word in the value, set FLAG 1, or 0. I am trying to use the below code but it errors it.

t[t['STATUS'].str.contains('AMEND')] 

Upvotes: 3

Views: 54

Answers (2)

Ayush Ranjan
Ayush Ranjan

Reputation: 101

This could be one way to do it

mydat.loc[mydat['Status']=="",'flag']=0
mydat.loc[mydat['Status']=="AMEND ORDER",'flag']=1

Status flag

0 AMEND ORDER 1.0

1 AMEND ORDER 1.0

  1. "............." 0.0

3 AMEND ORDER 1.0

4 ".............." 0.0

Upvotes: 0

jezrael
jezrael

Reputation: 862641

If empty are missing values or Nones chain another mask by | for bitwise OR and cast to integers for True -> 1, False - > 0 mapping:

t['FLAG'] = (t['STATUS'].str.contains('AMEND') | t['STATUS'].isna()).astype(int)

If empty is empty string compare values by Series.eq:

t['FLAG'] = (t['STATUS'].str.contains('AMEND') | t['STATUS'].eq('')).astype(int)

Upvotes: 2

Related Questions