【问题标题】:Multiple if conditions in pandas dataframe - Python熊猫数据框中的多个if条件 - Python
【发布时间】:2022-01-02 21:42:56
【问题描述】:

我正在关注this question的回答

我有一个这样的df

score_1   score_2  
1.11        NaN      
2.22        3.33      
NaN         3.33      
NaN         NaN
........       

计算final_score的规则是我们要求至少有一个分数是non-null,如果其中一个分数为NULL,那么final_score将等于另一个分数(它有所有的权重) 这是要复制的代码:

import numpy as np
import pandas as pd

df = pd.DataFrame({
            'score_1': [1.11, 2.22, np.nan],
            'score_2': [np.nan, 3.33, 3.33]
        })

def final_score(df):
    if (df['score_1'] != np.nan) and (df['score_2'] != np.nan):
        print('I am condition one')
        return df['score_1'] * 0.2 + df['score_2'] * 0.8

    elif (df['score_1'] == np.nan) and (df['score_2'] != np.nan):
        print('I am the condition two')
        return df['score_2']

    elif (df['score_1'] != np.nan) and (df['score_2'] == np.nan):
        print('I am the condition three')
        return df['score_1']

    elif (df['score_1'] == np.nan) and (df['score_2'] == np.nan):
        print('I am the condition four')
        return np.nan

df['final_score'] = df.apply(final_score, axis=1)
print(df)

这给了我输出:

score_1   score_2  final_score
1.11        NaN       NaN
2.22        3.33      3.108
NaN         3.33      NaN
NaN         NaN       NaN
........ 

但我的预期输出如下:

score_1   score_2  final_score
1.11        NaN       1.11
2.22        3.33      3.108
NaN         3.33      3.33
NaN         NaN       NaN
........ 

第一行和第三行不是我期望的结果,有人可以帮助我,我的代码有什么问题吗?非常感谢。

【问题讨论】:

    标签: python pandas dataframe numpy nan


    【解决方案1】:

    让我们使用 np.where 应用您的条件

    df['final_score'] =np.where(df.notna().all(1),df['score_1'] * 0.2 + df['score_2'] * 0.8,df.mean(1))
    
    
    
       score_1  score_2  final_score
    0     1.11      NaN        1.110
    1     2.22     3.33        3.108
    2      NaN     3.33        3.330
    3      NaN      NaN          NaN
    

    【讨论】:

    • 您好,谢谢,这更加简化了,但对于不熟悉我在做什么的人来说不是很可读,只是想知道为什么我们在这里使用df.mean(1)
    • df.mean(1) 沿轴 1 表示沿行的平均值。 np.where(条件,如果条件是则应用,如果不满足条件则应用此)
    • 嗨,如果我仍然想使用我的原始代码,我该如何更新它以使其工作?因为当有很多其他列时,您的单行代码似乎不适用于我的“大型”数据集,所以我仍然想弄清楚我的原始代码中的问题是什么,谢谢。
    • np.where 是矢量化的并且速度更快,除非速度和计算资源不是问题
    • df['final_score'] =np.where(df[['score_1','score_2']].notna().all(1),df['score_1'] * 0.2 + df['score_2'] * 0.8,df.mean(1))。试试看,让我知道。在手机上打字所以没有测试。基本上将两列子集以检查它们是否都是 NaN
    【解决方案2】:

    使用 np.isnan() 进行比较应该可以解决问题

    【讨论】:

    • 嗨,你能说得更具体些吗?我试过elif df['score_1'].isnan() and df['score_2'].notnan(): 但没有工作
    • 我的意思是按以下方式使用 np.isnan():elif (np.isnan(df['score_1']) and not np.isnan(df['score_2'])):
    猜你喜欢
    • 2020-10-14
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 2019-07-31
    • 2019-02-26
    • 2019-05-02
    • 1970-01-01
    • 2017-11-03
    相关资源
    最近更新 更多