Posts: 52
Threads: 26
Joined: May 2019
Jul-13-2019, 10:15 AM
(This post was last modified: Jul-13-2019, 10:23 AM by scidam.)
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'
Posts: 817
Threads: 1
Joined: Mar 2018
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
Posts: 52
Threads: 26
Joined: May 2019
I want to add a new column, for this condition.
Posts: 817
Threads: 1
Joined: Mar 2018
(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.
Posts: 52
Threads: 26
Joined: May 2019
Jul-13-2019, 12:14 PM
(This post was last modified: Jul-13-2019, 12:15 PM by SriMekala.)
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?
Posts: 817
Threads: 1
Joined: Mar 2018
(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.
|