簡體   English   中英

帶有數據框的條件語句/If 語句

[英]Conditional statement / If statement with Dataframes

我正在嘗試根據多個列“類”和“值”為“百分比”列分配一個值

下面是一個包含我的 dataframe 的鏈接: https://filebin.net/fo2wk7crmwf0fycc

這是我要應用的邏輯:

If df['Class'] equals 2 or 3, and if df['Value'] is less than 0.5, set df['Percentage'] to 0
If df['Class'] equals 2 or 3, and if df['Value'] is > 0.5 and <= 0.7, set df['Percentage'] to 0.25
If df['Class'] equals 2 or 3, and if df['Value'] is > 0.7 and <= 0.9, set df['Percentage'] to 0.5
Else set df['Percentage'] to 1

下面是我正在尋找的 output 的示例:

Class 價值 百分比
2 0.01 0
2 0.6 0.25
3 0.9 0.5
3 3 1

謝謝

searchsorted

使用searchsorted時,在這種情況下,您不需要包括01之類的邊界。

bins =  np.array([.5, .7, .9])
labels = np.array([0, .25, .5, 1])
cut = bins.searchsorted(df.Value)
results = labels[cut]

df.assign(Percentage=np.where(df['Class'].isin([2, 3]), results, 1))

       Class     Value  Percentage
0          2  0.000620         0.0
1          2  0.000620         0.0
2          3  0.001240         0.0
3          4  0.000620         1.0
4          5  0.000620         1.0
...      ...       ...         ...
14782      5  0.001178         1.0
14783      2  0.001116         0.0
14784      3  0.001178         0.0
14785      5  0.000310         1.0
14786      5  0.001116         1.0

[14787 rows x 3 columns]

Pandas cut

使用pd.cut時,您確實需要邊界,因為Pandas將創建間隔。

#                        / boundaries \
#                       ↓              ↓
cut = pd.cut(df.Value, [0, .5, .7, .9, 1], labels=[0, .25, .5, 1])

df.assign(Percentage=np.where(df['Class'].isin([2, 3]), cut, 1))

       Class     Value  Percentage
0          2  0.000620         0.0
1          2  0.000620         0.0
2          3  0.001240         0.0
3          4  0.000620         1.0
4          5  0.000620         1.0
...      ...       ...         ...
14782      5  0.001178         1.0
14783      2  0.001116         0.0
14784      3  0.001178         0.0
14785      5  0.000310         1.0
14786      5  0.001116         1.0

[14787 rows x 3 columns]

您還可以使用純np.where如下所示:

import numpy as np    
df['Percentage'] = np.where((df['Class'].isin([2, 3]) & (df['Value'] <= 0.5)), 0, 
                            np.where((df['Class'].isin([2, 3]) & (df['Value'] > 0.5) & (df['Value'] <= 0.7)), 0.25,
                                np.where((df['Class'].isin([2, 3]) & (df['Value'] > 0.7) & (df['Value'] <= 0.9) ), 0.5, 1)))

np.where就像你可以輕松理解的 if-then-else 條件語句。

       Class     Value  Percentage
0          2  0.000620         0.0
1          2  0.000620         0.0
2          3  0.001240         0.0
3          4  0.000620         1.0
4          5  0.000620         1.0
...      ...       ...         ...
14782      5  0.001178         1.0
14783      2  0.001116         0.0
14784      3  0.001178         0.0
14785      5  0.000310         1.0
14786      5  0.001116         1.0

[14787 rows x 3 columns]

暫無
暫無

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

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