在Python中为多个类别变量创建虚拟变量

在Python中为多个类别变量创建虚拟变量,python,pandas,machine-learning,Python,Pandas,Machine Learning,在dataframe df中有两列,我想将它们更改为无序的分类变量。有没有更有效的方法来实现这一点,而不是单独完成每一项?我在想以下方法: patient_dummies = pd.get_dummies(df['PatientSerial'], prefix='Serial_', drop_first = True) df = pd.concat([df, patient_dummies], axis = 1) df.drop(['PatientSerial'], inplace = True

在dataframe df中有两列,我想将它们更改为无序的分类变量。有没有更有效的方法来实现这一点,而不是单独完成每一项?我在想以下方法:

patient_dummies = pd.get_dummies(df['PatientSerial'], prefix='Serial_', drop_first = True)
df = pd.concat([df, patient_dummies], axis = 1)
df.drop(['PatientSerial'], inplace = True, axis = 1)


machine_dummies = pd.get_dummies(df['MachineID'], drop_first = True)
df = pd.concat([df, machine_dummies], axis = 1)
df.drop(['MachineID'], inplace = True, axis = 1)
但这不起作用;它为所有条目生成“nan”,而不是0和1

Yes:接受
参数。如果从DataFrame传递列名,它会将这两列作为传递的整个DataFrame的一部分返回dummified

patient_dummies = pd.get_dummies(df['PatientSerial'], prefix='Serial_', drop_first = True)
machine_dummies = pd.get_dummies(df['MachineID'], drop_first = True)
df = pd.concat([df, patient_dummies + machine_dummies], axis = 1)
df.drop(['PatientSerial','MachineID'], inplace = True, axis = 1)
例如:

df = pd.get_dummies(df, columns=['PatientSerial', 'MachineID'], drop_first=True)
np.random.seed(444)
v = np.random.choice([0, 1, 2], size=(2, 10))
df = pd.DataFrame({'other_col': np.empty_like(v[0]),
                   'PatientSerial': v[0],
                   'MachineID': v[1]})

pd.get_dummies(df, columns=['PatientSerial', 'MachineID'],
               drop_first=True, prefix=['Serial', 'MachineID'])

   other_col  Serial_1  Serial_2  MachineID_1  MachineID_2
0          2         0         0            0            1
1          1         0         0            0            1
2          2         0         0            0            0
3          2         1         0            1            0
4          2         0         1            0            0
5          2         1         0            0            1
6          2         0         1            0            0
7          2         1         0            0            1
8          2         1         0            0            0
9          2         1         0            0            1