简体   繁体   中英

Change the values of a dataframe, based on condition

Case statement inside the data frame, what am I doing wrong here?

df1['Response'] = [4 if x =='Closed with monetary relief' 
               3 if x =='Closed with non-monetary relief'
               2 if x =='Closed with explanation' 
               1 if x =='Closed' 
               0 if x =='Untimely response' for x in df1['Response']] 

Error I see:

3 if x =='Closed with non-monetary relief' ^ SyntaxError: invalid syntax

I think here is best use Series.map by dictionary:

d = {'Closed with monetary relief' : 4,
     'Closed with non-monetary relief':3.
     'Closed with explanation':2,
     'Closed':1,
     'Untimely response':0}

df1['Response'] = df1['Response'].map(d)

If some value not match get missing value, you can replace it by original:

df1['Response'] = df1['Response'].map(d).fillna(df1['Response'])

Or by some another value eg -1 , then also convert values to integers, because at least one NaN create float s column:

df1['Response'] = df1['Response'].map(d).fillna(-1).astype(int)

Try this format, it should work:

df1.Response.apply(lambda x: 4 if x =='Closed with monetary relief' else
               3 if x =='Closed with non-monetary relief' else
               2 if x =='Closed with explanation' else
               1 if x =='Closed' else
               0 if x =='Untimely response' else None )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM