如何在保留列的情况下找到累积计数行之间的差异

3

我有以下数据:

machine_id  time_to_failure
430494        1000
430494        700
430494        500
430494        100
430495        1000
430495        200

故障时间数据是从参考日0开始计算的,我希望将其转换为上次故障发生后的时间:

machine_id  time_to_failure
430494        300
430494        200
430494        400
430494        100
430495        800
430495        200

我尝试使用groupby和pivoting将重复的行转换为新列进行减法。但是,我想在原地进行操作以保留其他列。

1个回答

2

我们尝试使用groupby().diff()

df['time_to_failure'] = (df.groupby('machine_id')
                            ['time_to_failure'].diff(-1)
                           .fillna(df['time_to_failure'])
                        )

输出:

   machine_id  time_to_failure
0      430494            300.0
1      430494            200.0
2      430494            400.0
3      430494            100.0
4      430495            800.0
5      430495            200.0

错误:"无法从重复的轴进行重新索引"。这是因为我在多个列上使用了groupby吗?错误来自fillna行。 - Sample_friend
machine_id是您的数据索引吗? - Quang Hoang
这是一列数据。 - Sample_friend
想不出其他原因了。它对样本数据有效。还要检查索引是否有重复。 - Quang Hoang
1
搞定了!我在连接时需要重置索引。谢谢! - Sample_friend

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接