关于在不删除任何列的情况下取消堆叠 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 |
最佳答案
您可以使用 get_dummies
与 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
关于python - Pandas 拆单列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36009990/