你可以在这里使用简称:
# 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的“地方”的方法。尽管它似乎不喜欢“和”关键字,但它只适用于“&”和“|”。 有没有办法使用熊猫分配值而不是numpy?我看到它返回一个bools列表。你将不得不用它作为面具或什么?寻找类似的东西,“如果col1和col2符合某些条件,col3 = col1/col2,否则无” – nickm
@nickm是的,您可以使用布尔序列作为您需要的任何值的掩码。还有一个pandas [where](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html),略有不同。 – pansen