条件语句/带有数据框的if语句

3

我正在尝试根据多个列 'Class' 和 'Value' 为列 'Percentage' 分配一个值。

以下是包含数据框的链接: 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

下面是我所期望的输出示例:
分类 数值 百分比
2 0.01 0
2 0.6 25%
3 0.9 50%
3 3 100%
谢谢
2个回答

3

Numpy和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]

1

您也可以像下面这样使用纯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]

1
非常感谢,这个解决方案完美地运作了! - user11427018

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接