熊猫拆开单列

Raf*_*afa 4 python pandas

任何建议在column=periodo_dia不丢弃任何列的情况下拆散?

原始数据框如下所示:

|   | year | month | day | periodo_dia | valor_medida | Score_recogida |
|---|------|-------|-----|-------------|--------------|----------------|
| 0 | 2015 | 4     | 18  | manana      | 25.0         | 8.166667       |
| 1 | 2015 | 4     | 18  | noche       | 47.5         | 0.000000       |
| 2 | 2015 | 4     | 18  | tarde       | 20.0         | 0.000000       |
| 3 | 2015 | 4     | 19  | manana      | 0.0          | 0.000000       |
| 4 | 2015 | 4     | 19  | noche       | 0.0          | 4.066667       |
Run Code Online (Sandbox Code Playgroud)

期望的数据框应该是:

| year | month | day | manana | tarde | noche | valor_medida | Score_recogida |
|------|-------|-----|--------|-------|-------|--------------|----------------|
| 2015 | 4     | 18  | 1      | 0     | 0     | 25.0         | 8.166667       |
| 2015 | 4     | 18  | 0      | 0     | 1     | 47.5         | 0.000000       |
| 2015 | 4     | 18  | 0      | 1     | 0     | 20.0         | 0.000000       |
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 5

您可以使用get_dummieswith astype转换值integer,drop以及concat:

df1 = pd.get_dummies(df['periodo_dia']).astype(int)
print df1
   manana  noche  tarde
0       1      0      0
1       0      1      0
2       0      0      1
3       1      0      0
4       0      1      0

#drop column periodo_dia
df = df.drop('periodo_dia',axis=1)

print pd.concat([df, df1], axis=1)
   year  month  day  valor_medida  Score_recogida  manana  noche  tarde
0  2015      4   18          25.0        8.166667       1      0      0
1  2015      4   18          47.5        0.000000       0      1      0
2  2015      4   18          20.0        0.000000       0      0      1
3  2015      4   19           0.0        0.000000       1      0      0
4  2015      4   19           0.0        4.066667       0      1      0
Run Code Online (Sandbox Code Playgroud)