你可以在這裏使用簡稱:
# 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