我無法在 Pandas 中制定這個在 excel 中非常簡單的陳述句。我有一個資料框示例如下:
colA colB colC
10 0 27:15 John Doe
11 0 24:33 John Doe
12 1 29:43 John Doe
13 Inactive John Doe None
14 N/A John Doe None
顯然資料框比這大得多,有 10,000 多行,所以我試圖找到一種更簡單的方法來做到這一點。我想創建一個列來檢查 colA 是否等于 0 或 1。如果是,則等于 colC。如果不是,則等于 colC。在 excel 中,我只需創建一個新列 (new_col) 并撰寫
=IF(OR(A2<>0,A2<>1),B2,C2)
然后拖動填充整個作業表。
我敢肯定這很簡單,但我一生都無法弄清楚這一點。
結果應該是這樣的
colA colB colC new_col
10 0 27:15 John Doe John Doe
11 0 24:33 John Doe John Doe
12 1 29:43 John Doe John Doe
13 Inactive John Doe None John Doe
14 N/A John Doe None John Doe
uj5u.com熱心網友回復:
np.where 應該做的伎倆。
df['new_col'] = np.where(df['colA'].isin([0, 1]), df['colB'], df['colC'])
uj5u.com熱心網友回復:
這是一個解決方案,可根據您的條件將結果添加到串列中,然后將該串列作為 D 列添加回資料框中。
your_results=[]
for i,data in enumerate(df["colA"]):
if data==0 or data==1:
your_results.append(df["colC"][i])
else:
your_results.append(df["colB"][i])
df["colD"]=your_results
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/414784.html
標籤:
