另一列不随时间变化

2024-06-28 19:17:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据帧:

unit start stop A 0.0 8.15 A 9.18 11.98 A 13.07 13.80 B 13.82 15.00 B 16.46 17.58 A 17.62 17.98 B 18.01 19.99 B 20.10 25.11

如何创建执行以下操作的4列:

连续单位计数(两列,每个单位一列)

此列保留单位更改前发生的连续单位数量的连续计数。单位更改后重置为0

连续单位时间(两列,每个单位一列)

此列保留每行开始和停止之间的时间量的运行计数,直到单位发生变化。单位更改后,它也会重置为0

生成的df应如下所示:

unit start stop unitA_tally unitA_time unitB_tally unitB_time A 0.0 8.15 0 8.15 0 0 A 9.18 11.98 1 10.95 0 0 A 13.07 13.80 2 11.68 0 0 B 13.82 15.00 0 0 0 1.18 B 16.46 17.58 0 0 1 2.30 A 17.62 17.98 0 0.36 0 0 B 18.01 19.99 0 0 0 1.98 B 20.10 25.11 0 0 1 6.99

Tags: 数据df数量time时间unit单位start
1条回答
网友
1楼 · 发布于 2024-06-28 19:17:01

你实际上在找tally=cumcount, time=cumsum。所以我会这么做:

# these are the blocks
s = df['unit'].ne(df['unit'].shift()).cumsum()

# time for each row
times = df['stop'] - df['start']

# compute the new df 
new_df = (times.groupby(s)
            .agg(tally='cumcount', time='cumsum')  
            .assign(unit=df['unit'])               
            .pivot(columns='unit', 
                   values=['tally', 'time'])
            .fillna(0)
         )

# rename the columns
new_df.columns = [f'unit{y}_{x}' for x,y in new_df.columns]

# concat
pd.concat((df, new_df), axis=1)

输出:

  unit  start   stop  unitA_tally  unitB_tally  unitA_time  unitB_time
0    A   0.00   8.15          0.0          0.0        8.15        0.00
1    A   9.18  11.98          1.0          0.0       10.95        0.00
2    A  13.07  13.80          2.0          0.0       11.68        0.00
3    B  13.82  15.00          0.0          0.0        0.00        1.18
4    B  16.46  17.58          0.0          1.0        0.00        2.30
5    A  17.62  17.98          0.0          0.0        0.36        0.00
6    B  18.01  19.99          0.0          0.0        0.00        1.98
7    B  20.10  25.11          0.0          1.0        0.00        6.99

相关问题 更多 >