繁体   English   中英

基于多个条件选择填充数据框列

[英]Filling a dataframe column based on multiple conditional choices

我有一个数据框data ,看起来像:

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

输入“假日”,“报告”和“操作”列。通过查看其他一些数据列来计算功效。 我正在寻找一行代码,如果'Holiday','Report'或'Actions'中的任何一栏设置为1,则可以将功效设置为零。

我可以一次在一列上执行此过程:

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))

但是有没有一种方法可以将它们与一个OR语句组合成一个函数?

非常感谢

您可以通过切片子选择行,将其与1进行比较,并使用param axis=1 any行,并创建一个布尔掩码以传递给loc以根据需要将仅满足条件的行设置为1

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

希望这有助于使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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