簡體   English   中英

比較兩列以在 python 中創建第三列

[英]Compare two columns to create third column in python

這很簡單,但我不確定我哪里出錯了。 如果其他兩列也等於 1,則希望創建值為 1 的第三列。

這是我正在使用的代碼。 建議表示贊賞 - 我對 python 顯然很陌生。 提前致謝!

conditions = [
    (db3['voted_2018'] == 1) & (db3['voted_2020'] == 1)]

db3['voted_both_elections'] = np.select(conditions, 1,0)
db3 = pd.DataFrame({'voted_2018': [1, 0, 1, 1], 'voted_2020': [1, 1, 0, 1]})
conditions = db3['voted_2018'].eq(1) & db3['voted_2020'].eq(1)
db3['voted_both_elections'] = np.where(conditions, 1, 0)
print(db3)

更短:

db3['voted_both_elections'] = (db3['voted_2018'].eq(1) & db3['voted_2020'].eq(1)).astype(int)
   voted_2018  voted_2020  voted_both_elections
0           1           1                     1
1           0           1                     0
2           1           0                     0
3           1           1                     1

您可以先刪除conditions定義中的方括號。 方括號使變量成為列表,但在您的情況下,在括號內使用系列 object 會更容易:

conditions = (db3['voted_2018'] == 1) & (db3['voted_2020'] == 1)

然后,您可以使用 DataFrame's.loc 方法,並將條件用作行選擇的掩碼:

db3['voted_both_elections'] = 0
db3.loc[conditions, 'voted_both_elections'] = 1

一個更簡單的單線將是:

db3['voted_both_elections'] = conditions.astype(int)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM