簡體   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