Ted*_*Ted 2 python machine-learning pandas
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)
Run Code Online (Sandbox Code Playgroud)
我想将数据框 df 中的两列更改为无序的分类变量。有没有更有效的方法来实现这一点,而不是单独做每一个?我想到了以下方法:
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)
Run Code Online (Sandbox Code Playgroud)
但这没有用;它为所有条目生成了“nan”,而不是 0 和 1。
是:pandas.get_dummies()接受一个columns参数。如果您从您的 DataFrame 传递列名称,它会返回这两个列,作为您传递的整个 DataFrame 的一部分。
df = pd.get_dummies(df, columns=['PatientSerial', 'MachineID'], drop_first=True)
Run Code Online (Sandbox Code Playgroud)
例如:
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
Run Code Online (Sandbox Code Playgroud)