Specifying multiple columns names with the same prefix efficiently

Viewed 1417

I am running a regression with my observation being at the company level. I want to control for the type of company [what does it produce]. I have this information in an object variable which I turn into categorical and then get the dummies out of it.

df['Product Type'] = df['Product Type'].astype('category')
df =  pd.get_dummies(df, columns=['Product Type']).head()  

My sample is quite large and I end up getting a lot of dummy variables. It is quite a lot of work to introduce them into my model one by one (there might be 10-15 of them).

reg = sm.OLS(endog=df['Y'], exog= df[['X1', 'Number of workers', 'X2', "Product Type_Jewellery", "Product_Type_Apparel", (all the other product dummies) ]], missing='drop')

Is there a more efficient way to do this? In stata, I used the prefix i.Product_Type which would signal to the software that the String variable had to be considered as a categorical one... anything similar?

3 Answers

Use str.contains to find the columns that contain "Product_*", and accessing them becomes easy.

c = df.columns[df.columns.str.contains('Product')]

If regex is not needed, you can initialise c as

c = df.columns[df.columns.str.contains('Product', regex=False)]

Or, using str.startswith:

c = df.columns[df.columns.str.startswith('Product')]

Or, a list comprehension:

c = [c_ for c_ in df if c_.startswith('Product')]

Finally, access the subset by unpacking c:

subset = df[['X1', 'Number of workers', 'X2', *c]]
reg = sm.OLS(endog=df['Y'], exog=subset, missing='drop')

Same idea like what cold provided by using filter

sm.OLS(endog=df['Y'], 
       exog=df.filter(regex=r'X1|X2|Number|Product'), 
       missing='drop')

Using the statsmodels.formula.api you don't need to generate the dummies yourself. Remove spaces from you column names and reference the Categorical column with C(col_name)

import statsmodels.formula.api as smf

df = df.rename(columns={'Product Type': 'Product_Type',
                        'Number of workers': 'Number_of_workers'})

results = smf.ols(formula = 'Y ~ X1 + X2 + Number_of_workers + C(Product_Type)', 
                  data=df, missing='drop').fit()

Sample Data

import pandas as pd
import numpy as np
np.random.seed(123)
df = pd.DataFrame({'Y': np.random.randint(1,100,200),
                   'X1': np.random.normal(1,20,200),
                   'X2': np.random.normal(-10,1,200),
                   'Number of workers': np.arange(1,201,1)/10,
                   'Product Type': np.random.choice(list('abcde'), 200)})

Output of results.summary()

========================================================================================
                           coef    std err          t      P>|t|      [0.025      0.975]
----------------------------------------------------------------------------------------
Intercept               69.2836     23.105      2.999      0.003      23.711     114.856
C(Product_Type)[T.b]    11.3334      6.941      1.633      0.104      -2.356      25.023
C(Product_Type)[T.c]     1.3745      6.943      0.198      0.843     -12.321      15.070
C(Product_Type)[T.d]     2.0430      6.258      0.326      0.744     -10.300      14.386
C(Product_Type)[T.e]     3.8445      6.273      0.613      0.541      -8.528      16.217
X1                       0.0207      0.113      0.184      0.854      -0.202       0.243
X2                       1.4677      2.177      0.674      0.501      -2.825       5.761
Number_of_workers       -0.5803      0.369     -1.573      0.117      -1.308       0.147
==============================================================================

Notice, that with the formulas api since your products create a complete basis it will automatically drop one of the categories since we have the intercept, similar to what you would find in stata.

Related