首页 > 解决方案 > 在 Pandas 中跨多个列的 if 语句

问题描述

这是我拥有的数据:

| total |  big  |  med  | small| big_perc | med_perc | sml_perc |
|:-----:|:-----:|:-----:|:----:|:--------:|:--------:|:--------:| 
|   5   |   4   |   0   |   1  |   0.8    |   0.0    |   0.2    |
|   6   |   0   |   3   |   3  |   0.0    |   0.5    |   0.5    | 
|   5   |   2   |   3   |   0  |   0.4    |   0.6    |   0.0    |

这就是我想要创建的:

| total |  big  |  med  | sml  | big_perc | med_perc | sml_perc | condition |   size  |
|:-----:|:-----:|:-----:|:----:|:--------:|:--------:|:--------:|:--------: |:--------:
|   5   |   4   |   0   |   1  |   0.8    |   0.0    |   0.2    |    YES    |   big   |
|   6   |   0   |   3   |   3  |   0.0    |   0.5    |   0.5    |    NO     |         | 
|   5   |   2   |   3   |   0  |   0.4    |   0.6    |   0.0    |    YES    |   med   | 

对于条件列 id,如果 big_perc、med_perc 或 sml_perc 大于 0.6 则表示“是”,如果不满足该条件则为空白。

对于大小列 id 来说,无论哪一列大于 0.6,否则也为空白

这是我尝试过的:

for (df['condition'] in len(df):

    if df['big_perc'] >= 0.60:
        df['condition'] = 'YES'
    elif df['med_perc'] >= 0.60:
        df['condition'] = 'YES'
    elif df['sml_perc'] >= 0.60:
        df['condition'] = 'YES'
    else: 
        df['condition'] = ''

我为 size 列尝试了相同的 for/if 语句

标签: pythonpandasdataframe

解决方案


对于condition列,np.where就足够了,因为它只是一个条件;但是对于该size列,由于它具有多个条件,因此 np.select应该适合:

df["condition"] = np.where(df.filter(like="perc").ge(0.6).any(axis=1), "YES", "NO")

cond1 = df.filter(like="perc").gt(0.6).any(axis=1)
cond2 = df.filter(like="perc").ge(0.6).any(axis=1)
cond3 = df.filter(like="perc").lt(0.6).all(axis=1)
condlist = [cond1, cond2, cond3]
choicelist = ["big", "med", ""]

df["size"] = np.select(condlist, choicelist)


    total   big med small   big_perc    med_perc sml_perc condition size
0   5        4  0   1       0.8         0.0         0.2    YES      big
1   6        0  3   3       0.0         0.5         0.5    NO   
2   5        2  3   0       0.4         0.6         0.0    YES      med

推荐阅读