I have a dataframe data
which looks like:
Holiday Report Action Power
0 0 0 1.345
0 0 0 1.345
1 0 0 0
0 0 0 1.345
0 0 0 1.345
0 1 0 0
0 0 0 1.345
0 1 1 0
0 0 0 1.345
0 0 1 0
Columns 'Holiday', 'Report' and 'Actions' are pulled in. Power is calculated by looking a some other columns of data. I am looking for a line of code that will allow me to set the power to zero if any of the columns 'Holiday', 'Report' or 'Actions' is set to 1.
I can do this procedure one column at a time:
data.loc[staticidx, "power"] = np.where(dayData.Holiday = 1, 0, (a - b)/(c-1))
data.loc[staticidx, "power"] = np.where(dayData.Report= 1, 0, (a - b)/(c-1))
data.loc[staticidx, "power"] = np.where(dayData.Actions= 1, 0, (a - b)/(c-1))
but is there a way to combine them into one function with something like an OR statement?
Many thanks
You can subselect the rows by slicing, compare against 1 and use any
with param axis=1
and create a boolean mask passing to loc
to set only those rows that meet the condition to 1
as desired:
In [23]:
df.loc[(df.ix[:,:'Action'] == 1).any(axis=1), 'Power'] = 1
df
Out[23]:
Holiday Report Action Power
0 0 0 0 1.345
1 0 0 0 1.345
2 1 0 0 1.000
3 0 0 0 1.345
4 0 0 0 1.345
5 0 1 0 1.000
6 0 0 0 1.345
7 0 1 1 1.000
8 0 0 0 1.345
9 0 0 1 1.000
Hope this helps using np.where
:
In[49]:df['Power']=np.where((df['Holiday']==1)|(df['Report']==1)|(df['Action']==1),1,df['Power'])
In[50]:df
Out[50]:
Holiday Report Action Power
0 0 0 0 1.345
1 0 0 0 1.345
2 1 0 0 1.000
3 0 0 0 1.345
4 0 0 0 1.345
5 0 1 0 1.000
6 0 0 0 1.345
7 0 1 1 1.000
8 0 0 0 1.345
9 0 0 1 1.000
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.