【问题标题】:Making a new column in pandas based on conditions of other columns根据其他列的条件在 pandas 中创建一个新列
【发布时间】:2017-08-26 21:27:56
【问题描述】:

我想根据 if 语句创建一个新列,该语句在数据框中具有两个或多个其他列的条件。

例如,column3 = True if (column1 0.0)。

我环顾四周,似乎其他人使用了带有 lambda 函数的 apply 方法,但我对这些有点新手。

我想如果每列都满足条件,我可以添加两个额外的列,使该行为 1,然后对列求和以检查是否满足所有条件,但这似乎有点不雅。

如果您使用 apply/lambda 提供答案,假设数据帧名为 sample_df,列是 col1、col2 和 col3。

非常感谢!

【问题讨论】:

    标签: python pandas dataframe lambda apply


    【解决方案1】:

    这里可以简称为eval

    # create some dummy data
    df = pd.DataFrame(np.random.randint(0, 10, size=(5, 2)), 
                      columns=["col1", "col2"])
    print(df)
    
        col1    col2
    0   1       7
    1   2       3
    2   4       6
    3   2       5
    4   5       4
    
    df["col3"] = df.eval("col1 < 5 and col2 > 5")
    print(df)
    
        col1    col2    col3
    0   1       7       True
    1   2       3       False
    2   4       6       True
    3   2       5       False
    4   5       4       False
    

    您也可以通过(df["col1"] &lt; 5) &amp; (df["col2"] &gt; 5) 编写不带 eval 的代码。

    您还可以使用np.where 增强示例,以立即明确设置positivenegative 情况的值:

    df["col4"] = np.where(df.eval("col1 < 5 and col2 > 5"), "Positive Value", "Negative Value")
    print(df)
    
        col1    col2    col3    col4
    0   1       7       True    Positive Value
    1   2       3       False   Negative Value
    2   4       6       True    Positive Value
    3   2       5       False   Negative Value
    4   5       4       False   Negative Value
    

    【讨论】:

    • 谢谢,我使用了numpy的“where”方法。虽然它似乎不喜欢“and”关键字,但它只适用于“&”和“|”。有没有办法使用 pandas 而不是 numpy 来分配值?我看到它返回一个布尔列表。您是否必须将其用作面具或其他东西?寻找类似的东西,“如果 col1 和 col2 满足某些条件,col3 = col1/col2,否则没有”
    • @nickm 是的,您可以使用布尔系列作为您需要的任何值的掩码。还有一只熊猫where,略有不同。
    猜你喜欢
    • 2020-06-02
    • 2020-04-25
    • 2020-09-24
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    相关资源
    最近更新 更多