Python Forum
How to use cse insensitive condition in lambda expresion
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to use cse insensitive condition in lambda expresion
I want to add 'value' column, and if 'Status' column contains pass(case insensitive) give value is 0 in 'value' column. I use below code, but only giving zero in3rd (but it should give 'zeor" in rows 0,2,3,5.

import pandas as pd

df=pd.DataFrame({'Name':['NHAY', 'HAY','UTY','UIK', 'JUI','YTH'],'Status':['Pass','Running','pass(warning 0)','pass','fail','passed']})

df['value'] = df['Status'].apply(lambda x: '0' if x == 'pass' else '1',case=False)
it give some error:
TypeError: <lambda>() got an unexpected keyword argument 'case'
You don't need to use .apply here, just select appropriate rows and set a new value, e.g.

df.loc[df['Status'].str.contains('pass', case=False), 'value'] = 0
I want to add a new column, for this condition.
(Jul-13-2019, 10:54 AM)SriMekala Wrote: I want to add a new column, for this condition.
I don't understand this, .loc selector automatically creates a new column if needed. In the code above a new column
named value is created. Probably, you need to add a line df.loc[:, 'value'] = df.Status before assigning zero values using the condition.
Just curious, If I do not have a "value" column, and I want to add the column in the same line and else condition:

df=pd.DataFrame({'Name':['NHAY', 'HAY','UTY','UIK', 'JUI','YTH'],'Status':['Pass','Running','pass(warning 0)','pass','fail','passed']})
df['value']=df.loc[df['Status'].str.contains('pass', case=False), 'value'] = 0 # Can I add else condition and new clolumn('value')here?
(Jul-13-2019, 12:14 PM)SriMekala Wrote: df['value']=df.loc[df['Status'].str.contains('pass', case=False), 'value'] = 0
Doing so you encounter with specificity of chained assignment in Python. This line is equivalent to
temporary = 0
df['value'] = temporary
df.loc[...] = temporary
So, you will get a column of zeros. df.loc[..., 'value'] automatically creates a column if it does not exist, you don't need to create it, e.g. by df['value'] or something else.

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020