Pandas展开单列

4

有没有建议可以在不删除任何列的情况下解除 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       |

期望得到的数据框应该是这样的:
| 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       |
2个回答

5

您可以使用get_dummiesastype将值转换为integer,使用dropconcat进行操作:

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

0
讨厌回答自己的问题,但希望能帮到其他人。这个可以完成任务:
df = pandas.concat([df.drop('periodo_dia',axis=1),
                    pandas.get_dummies(df['periodo_dia'])],axis=1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接