How to recode a single categorical variable into a dummy

Viewed 39

I am struggling to understand how to recode a categorical variable in a CSV file (originally named "smoker") into a dummy variable named "smoke".

This is my code currently, with notes for where the recoding should go:

import numpy as np

import pandas as pd

import statsmodels.formula.api as sms

from statsmodels.formula.api import ols

ins = pd.read_csv("insurance.csv")

# Recode the column smoker into a dummy variable with the prefix smoke

results = ols(formula='charges ~ age + bmi + smoke', data=ins)
model = results.fit()

aov_table = sms.stats.anova_lm(model, typ=2)

print(aov_table)
1 Answers

Not sure what your 'smoker' column looks like. You can try something like this.

df['smoke'] = np.where(df['smoker'] == "yes", 1, 0)

Again you will need to rearrange the coding based on your 'smoker' column's values

Related