根据熊猫中的时间戳分组生成值

时间:2019-02-23 19:56:47

标签: python pandas group-by

具有这样的Pandas数据框:

enter image description here

我们有时间戳记(time列和type列中的4个不同的机器部分:part_1,part_2,part_3,part_4和激活列,它们在其中仅具有值1它(它已被激活)。我想将其余类添加到每个时间戳,并为它们在activated列中添加0,如下所示:

enter image description here

我假设应该使用一些带有list的分组方法,但是我不知道该如何实现。熊猫有可能吗?

1 个答案:

答案 0 :(得分:1)

通过使用unstackstack

df.set_index(['time','type']).activation.unstack(fill_value=0).stack().reset_index()

或将pivotmelt一起使用

df.pivot(*df.columns).stack(dropna=False).fillna(0).reset_index()