簡體   English   中英

根據其他兩個變量的值創建一個變量

[英]Creating a variable based on the values of two other variables

我在 Pandas 中有一個數據框,其中包含兩個變量:DEC 和 TYPE

dec     type
 1        13
 2        2
 2        5
 2        7
 2        9
 3        5

從這兩個變量中,我想根據這兩個變量的值創建其他二進制變量。

我一直無法找到完全寫出我想要的代碼,但在 python 英語中,它會是這樣的:

df['new_variable'] = 1 if DEC == 1 & TYPE == 3 or 2 or 1

請讓我知道是否可以在我的問題中包含一些內容來澄清我正在尋找的內容。

從答案更新:

我遇到的一個問題是因為對於每個變量,我需要運行兩行代碼(如下),當我運行第二行時,它超出了第一行中的編碼。 我如何同時運行兩行(即第二行不超過第一行)?

harrington_citations['gov_winner'] =  np.where((harrington_citations['dec'] == 1) & harrington_citations['type'].isin([1,2,3,4,22]) , 1, 0)

harrington_citations['gov_winner'] = np.where((harrington_citations['dec'] == 2) & harrington_citations['type'].isin([1,5,9,13,18]), 1, 0)

看起來你需要.isin作為第二個條件並返回 1/0:

df['new_variable'] = (df['dec'].eq(1) & df['type'].isin([3,2,1])).view('i1')

編輯每個評論,您應該使用|創建 2 個條件條件:

c1 = (harrington_citations['dec'] == 1) & harrington_citations['type'].isin([1,2,3,4,22])
c2 = (harrington_citations['dec'] == 2) & harrington_citations['type'].isin([1,5,9,13,18])
harrington_citations['gov_winner'] = (c1|c2).view('i1')

np.nan替換為適合您的任何值:

df['new_variable'] = np.where((df['dec'] == 1) & df['type'].isin([1,2,3]), 1, np.nan)

暫無
暫無

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

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