I have created 3 new variables a,b and c using certain conditions. Now I want to assign these variables to a new column in a pandas DataFrame again using some conditions.
I want a code something like what I have written below but in a smarter way. The code below is working fine but it's not a smart solution. Is there a possibility to write a loop, maybe an iterative loop
df2['dest_col'] = np.where(df2['month'] == 'March-2016',a
,(np.where(df2['month'] == 'April-2016',b
,(np.where(df2['month'] == 'May-2016',c)))
You want numpy.select
:
cond=[(df2['month'] == month) for month in df2['month'].unique()]
values=[a, b, c]
df2['dest_col'] = np.select(cond,values)
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.