基于其他列的条件在pandas中创建新列

4
我想基于一个if语句创建一个新的列,该语句具有数据帧中两个或更多其他列的条件。
例如,当(column1 < 10.0)且(column2 > 0.0)时,column3 = True。
我查了一下,似乎别人使用了apply方法和lambda函数,但我在这方面还是个新手。
我想我可以创建两个附加列,如果每列满足条件,则将该行设置为1,然后对列求和以检查是否满足所有条件,但这似乎有点不太优雅。
如果您提供了一个使用apply/lambda的答案,假设数据帧名为sample_df,列名为col1、col2和col3。
非常感谢!
1个回答

2

您可以在此处使用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"] < 5) & (df["col2"] > 5)的方式不使用eval进行编写。
你还可以使用np.where来明确设置正面和反面的值,以增强示例:
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,否则为none”的东西。 - nickm
@nickm 是的,您可以使用布尔序列作为您需要的任何值的掩码。还有一个略有不同的pandas where - pansen

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