熊猫根据计数将行转换为列

时间:2021-03-23 03:36:07

标签: pandas dataframe

我有一个如图所示的数据框

enter image description here

我需要像这样转换它

enter image description here

这只是我的实际数据的示例虚拟副本。它有超过 5000 个 ID 和 20 个事件。

所以我需要每个 ID,每个事件单独触发的次数的总和,事件需要是单独的列。如何在 Pandas 中实现这一点?

1 个答案:

答案 0 :(得分:1)

你可以使用pandas pivot_table 函数

df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two',
                       'two','one','three'],
               'bar': ['A', 'B', 'C', 'A', 'B', 'C','A','A'],
               'baz': [1, 2, 3, 4, 5, 6,1,2],
               'zoo': ['x', 'y', 'z', 'q', 'w', 't','x','x']})
print(df)
    bar  baz  foo   zoo
0   A    1    one   x
1   B    2    one   y
2   C    3    one   z
3   A    4    two   q
4   B    5    two   w
5   C    6    two   t
6   A    1    one   x
7   A    2  three   x

df.pivot_table(index='foo',columns='bar',values='baz',aggfunc='count',fill_value=0)

bar    A    B   C
foo         
one    2    1   1
three  1    0   0
two    1    1   1

在这种情况下,您可能必须执行以下操作。

df = pd.DataFrame({'Event':['a','b','c','d','c','a','a'],'ID':['001','002','003','004','004','004','001']})
df = df.reset_index()
df.pivot_table(index='ID',columns='Event',values='index',aggfunc='count',fill_value=0)
Event   a   b   c   d
ID              
001     2   0   0   0
002     0   1   0   0
003     0   0   1   0
004     1   0   1   1