首页 > 解决方案 > 如何在python中为数据框的每个类别创建列

问题描述

我在数据框中有一列,它有 6 个分类变量。我想为每个类别创建 1 列。到目前为止,我一直在使用 pivot_table,但它似乎不是一个正确的答案,因为我不想使用任何 aggfunc 并且只想返回具有相同对应值的数据帧。下面在我的数据框示例中:

        Date        Region                  Total confirmed deaths (deaths)
6452    2020-03-03  Asia                    0
10514   2020-01-02  Asia                    0
1416    2020-01-21  Europe                  0
9595    2020-02-06  Asia                    1
12221   2020-01-07  Europe                  0
12828   2020-01-14  Rest of the world       1
6232    2020-03-07  Europe                  197
10812   2020-01-05  Rest of America         0
11984   2020-04-18  Rest of the world       37
6572    2020-03-28  Rest of the world       1
1297    2020-03-19  Asia                    1
4851    2020-03-20  Rest of the world       0

下面是我用于数据透视表的代码:

pivoted = df.pivot_table(index='Date', columns='Region', values='Total confirmed deaths (deaths)')

pivoted.resample('W')

标签: pythondataframe

解决方案


推荐阅读