簡體   English   中英

Python pandas 和 numpy:根據現有變量的多個條件為新變量分配數值

[英]Python pandas and numpy: assign numerical values to new variable based on multiple conditions for existing variables

這在 Excel 中是微不足道的,為什么在 Python 中這么難?

目標是根據幾個條件計算 state 變量,包括 state 變量的先前值。 值是已知的 integer,Min(3) 和 Max(3) 只是 3 個周期滾動 window 向前移動一個周期的最小值和最大值。 這就是我走多遠。

Index Value Max(3) Min(3) 
0     10    nan    nan    
1     20    nan    nan        
2     15    nan    nan         
3     25    20     10    
4     15    25     15     
5     10    25     15     
6     15    20     10         

根據以下條件計算 state 變量的最佳方法是什么:

  • a) 如果值 > Max(3) 則 1
  • b) 如果值 < Min(3) 則 4
  • c) 如果 Value <= Max(3) & Value >= Min (3) & previous State = 1 or 2 then 2
  • d) 如果 Value <= Max(3) & Value >= Min (3) & previous State = 4 or 3 then 3

在最終的 DataFrame 中應該如下所示:

Index Value Max(3) Min(3) State
0     10    nan    nan    nan
1     20    nan    nan    nan    
2     15    nan    nan    nan     
3     25    20     10     1
4     15    25     15     2
5     10    25     15     4
6     15    20     10     3    

我主要使用 np.where() 函數嘗試過這個,但是一旦我接近 c) 和 d) 條件,總是會遇到問題。

你可以使用這個:

df.loc[df.Value.gt(df['Max(3)']), 'State'] = 1
df.loc[df.Value.lt(df['Min(3)']), 'State'] = 4
df.loc[df.Value.between(df['Min(3)'], df['Max(3)']) & (df.State.shift(1).isin((3, 4))), 'State'] = 3
df.loc[df.Value.between(df['Min(3)'], df['Max(3)']) & (df.State.shift(1).isin((1,2))), 'State'] = 2

output:
在此處輸入圖像描述

解釋:
第一條語句檢查 df.Value 大於 df['Max(3)'] 的位置並創建一個新列“State”,其中填充了 NaN,並且條件位置只有 1s

seconds 行設置 4s,其中 df.Value 小於 df.['Min(3)']

最后兩個語句檢查 df.Value 是否在 Max(3) 和 Min(3) 范圍內,並比較 df.State 最后一個值 ( .shift )。 注意:如果數字是后續的,您也可以在此處使用.between代替.isin

np.select可以很好地處理多種條件,具有良好的可讀性

df['Value'] = df['Value'].astype(float)

conditions =
[
    df['Value']>df['Max(3)'],
    df['Value']<df['Min(3)'],
    (df['Value']<=df['Max(3)']) & (df['Value']>= df['Min(3)']) & (df['State'].shift().isin((1,2))),
    (df['Value']<=df['Max(3)']) & (df['Value']>= df['Min(3)']) & (df['State'].shift().isin((3,4)))
]

choicelist = [1, 4, 2, 3]

df['State'] = np.select(conditions, choicelist, np.nan)
print(df)
   Index  Value  Max(3)  Min(3)  State
0      0   10.0     NaN     NaN    NaN
1      1   20.0     NaN     NaN    NaN
2      2   15.0     NaN     NaN    NaN
3      3   25.0    20.0    10.0    1.0
4      4   15.0    25.0    15.0    2.0
5      5   10.0    25.0    15.0    4.0
6      6   15.0    20.0    10.0    3.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM