2017-07-12 37 views
0

我有這樣一個數據幀的交互虛擬變量:創建使用大熊貓或statsmodel爲兩列

Index ID Industry years_spend  asset 
6646 892   4   4 144.977037 
2347 315  10   8 137.749138 
7342 985   1   5 104.310217 
137 18   5   5 156.593396 
2840 381  11   2 229.538828 
6579 883  11   1 171.380125 
1776 235   4   7 217.734377 
2691 361   1   2 148.865341 
815 110  15   4 233.309491 
2932 393  17   5 187.281724 

我想創建爲它創建len(df.Industry.value_counts()) * len(df.years_spend.value_counts()) varaible,例如工業X years_spend虛擬變量d_11_4 = 1對於所有具有行業== 1和年花費= 4的行,否則d_11_4 = 0.然後,我可以將這些變量用於一些迴歸工作。

我知道我可以讓羣體喜歡什麼,我想用df.groupby([「產業」,「years_spend」]),我知道我可以在statsmodels創建這樣的變量使用patsy語法一列:

import statsmodels.formula.api as smf 

mod = smf.ols("income ~ C(Industry)", data=df).fit() 

,但如果我想有2列做我得到一個錯誤: IndexError: tuple index out of range

我怎麼能做到這一點與大熊貓或利用內幕statsmodels一些功能?

回答

2

你可以做這樣的事情,你必須首先創建一個封裝了Industryyears_spend計算字段:

df = pd.DataFrame({'Industry': [4, 3, 11, 4, 1, 1], 'years_spend': [4, 5, 8, 4, 4, 1]}) 
df['industry_years'] = df['Industry'].astype('str') + '_' + df['years_spend'].astype('str') # this is the calculated field 

這裏的df的樣子:

Industry years_spend industry_years 
0   4   4   4_4 
1   3   5   3_5 
2  11   8   11_8 
3   4   4   4_4 
4   1   4   1_4 
5   1   1   1_1 

現在你可以適用get_dummies

df = pd.get_dummies(df, columns=['industry_years']) 

這會得到你想要的東西:)

+0

謝謝我想出了使用for循環和布爾索引,但你告訴我一個更pythonic的方式。你有什麼想法我應該如何包括我的statsmodels迴歸這些假人?我應該使用'「」.join(['+ industry {}')格式(x)來表示範圍(10)中的x]])'還是有更好的方法。 – Mehdi

+0

也許創建industry_years列然後使用(「income_C(行業)」),data = df)爲迴歸創建虛擬是一個好主意。 – Mehdi

+1

@Mehdi,對不起,我沒有使用'statsmodels'進行建模,但我想你可以把所有的獨立變量放到一個列表變量中(使用'df.columns'並放下y列),然後構建一個字符串使用你之前給出的想法:'「+」。join(list_of_indep_vars)',然後使用''income_ string_you_just_built''創建你的模型。當然,這是假定'statsmodels'中定義迴歸公式的方法是'y〜x_1 + x_2 + x_3 ... x_n'。 –

0

使用帕齊語法,它只是:

import statsmodels.formula.api as smf 

mod = smf.ols("income ~ C(Industry):C(years_spend)", data=df).fit() 

:字的意思是「互動」;您還可以將其推廣到兩個以上項目(C(a):C(b):C(c))的交互作用,數字值和分類值之間的交互作用等。您可能會發現patsy docs useful