Python Forum
How to use cse insensitive condition in lambda expresion - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: How to use cse insensitive condition in lambda expresion (/thread-19758.html)



How to use cse insensitive condition in lambda expresion - SriMekala - Jul-13-2019

Hi,
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:
Error:
TypeError: <lambda>() got an unexpected keyword argument 'case'



RE: How to use cse insensitive condition in lambda expresion - scidam - Jul-13-2019

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



RE: How to use cse insensitive condition in lambda expresion - SriMekala - Jul-13-2019

I want to add a new column, for this condition.


RE: How to use cse insensitive condition in lambda expresion - scidam - Jul-13-2019

(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.


RE: How to use cse insensitive condition in lambda expresion - SriMekala - Jul-13-2019

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?



RE: How to use cse insensitive condition in lambda expresion - scidam - Jul-14-2019

(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.