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

问题描述 投票:0回答:1

拥有像这样的Pandas数据帧:

enter image description here

我们在time列中有时间戳(type列)和4个不同的机器部分:part_1,part_2,part_3,part_4和激活列,其中只有值1(它被激活)。我想将其余的类添加到每个时间戳,并在activated列中为它们添加0,就像这样:

enter image description here

我假设应该使用一些group-by方法,但我不知道如何做到这一点的方法。在熊猫中可以做到吗?

python pandas group-by
1个回答
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()
© www.soinside.com 2019 - 2024. All rights reserved.