代码之家  ›  专栏  ›  技术社区  ›  Aaraeus

对数据帧列使用条件if/else逻辑

  •  1
  • Aaraeus  · 技术社区  · 8 年前

    pw2 看起来像这样,我有两列,pw1和pw2,它们是获胜的概率。我想执行一些条件逻辑来创建另一个名为 WINNER 基于 pw1 电源2

    +-------------------------+-------------+-----------+-------------+
    |          Name1          |     pw1     |   Name2   |     pw2     |
    +-------------------------+-------------+-----------+-------------+
    | Seaking                 | 0.517184213 | Lickitung | 0.189236181 |
    | Ferrothorn              | 0.172510623 | Quagsire  | 0.260884258 |
    | Thundurus Therian Forme | 0.772536272 | Hitmonlee | 0.694069408 |
    | Flaaffy                 | 0.28681284  | NaN       | NaN         |
    +-------------------------+-------------+-----------+-------------+
    

    我想在函数中有条件地这样做,但我遇到了一些麻烦。

    • 电源1 &燃气轮机; Name1
    • 如果 &燃气轮机; Name2
    • 如果 电源1 已填充但 电源2
    • 如果 电源2 电源1 不是,用 姓名2

    但是我的函数不起作用-出于某种原因,检查值是否为null不起作用。

    def final_winner(df):
        # If PW1 is missing and PW2 is populated, Pokemon 1 wins
        if df['pw1'] = None and df['pw2'] != None:
            return df['Number1']
        # If it's the same thing but the other way around, Pokemon 2 wins
        elif df['pw2'] = None and df['pw1'] != None:
            return df['Number2']
        # If pw2 is greater than pw1, then Pokemon 2 wins
        elif df['pw2'] > df['pw1']:
            return df['Number2']
        else
            return df['Number1']
    
    pw2['Winner'] = pw2.apply(final_winner, axis=1)
    
    1 回复  |  直到 8 年前
        1
  •  6
  •   rafaelc    8 年前

    不要使用 apply ,非常慢。使用 np.where

    pw2 = df.pw2.fillna(-np.inf)
    df['winner'] = np.where(df.pw1 > pw2, df.Name1, df.Name2)
    

    一次 NaN 他总是输,我可以 fillna() -np.inf


    看看你的代码,我们可以指出几个问题。首先,你在比较 df['pw1'] = None ,这是用于比较的无效python语法。你通常想用 == 接线员。但是,对于 None ,建议使用 is ,例如 if variable is None: (...) pandas/numpy 环境中,实际上有多个空值( , , NaT 等)。

    因此,最好使用 pd.isnull() df.isnull()

    仅举个例子,您的代码应该是这样的:

    def final_winner(df):
        if pd.isnull(df['pw1']) and not pd.isnull(df['pw2']):
            return df['Name1']
        elif pd.isnull(df['pw2']) and not pd.isnull(df['pw1']):
            return df['Name1']
        elif df['pw2'] > df['pw1']:
            return df['Name2']
        else:
            return df['Name1']
    
    df['winner'] = df.apply(final_winner, axis=1)
    

    但同样,一定要使用 np.哪里