2017-04-01 101 views
1

我想根據if語句創建一個新的列,該if語句在數據框中具有兩個或更多其他列的條件。根據其他列的條件製作熊貓的新列

例如,column3 = True if(column1 < 10.0)and(column2> 0.0)。

我環顧四周,似乎其他人已經使用了lambda函數的apply方法,但是我對這些有點新手。

我想我可以做兩個額外的列,如果條件滿足每列,然後總結列檢查是否滿足所有條件,但這似乎有點不雅。

如果您使用apply/lambda提供答案,我們假設數據框稱爲sample_df,列爲col1,col2和col3。

非常感謝!

回答

1

你可以在這裏使用簡稱:

# 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 
+0

謝謝你,我用numpy的「地方」的方法。儘管它似乎不喜歡「和」關鍵字,但它只適用於「&」和「|」。 有沒有辦法使用熊貓分配值而不是numpy?我看到它返回一個bools列表。你將不得不用它作爲面具或什麼?尋找類似的東西,「如果col1和col2符合某些條件,col3 = col1/col2,否則無」 – nickm

+0

@nickm是的,您可以使用布爾序列作爲您需要的任何值的掩碼。還有一個pandas [where](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html),略有不同。 – pansen

相關問題