python - Pandas 拆单列

标签 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       |

所需的数据框应该是这样的:

| 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_dummiesastype用于将值转换为 integerdropconcat :

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/

相关文章:

python - 使用pip_pypy3安装pyarrow时出现 "Could NOT find Arrow"错误

python - 如何在 Eclipse/Python/Appengine 中使用持久本地 NDB 数据进行调试?

python - 如何使自定义类成为 Python 中的集合

python - Pandas date_range 从结束日期到开始日期

python - 广播 groupby 结果作为原始 DataFrame 中的新列

python - Pandas :拆分字符串,并计算值?

python - 根据索引和值条件选择 Pandas 系列的切片

python - 在组织内部分发我的 python 模块

python - 如何检查线程当前是否持有 GIL?

python - Pandas:如何在 MultiIndex 中格式化图例