对pandas数据框中列值更改的值求和



我有一个熊猫数据框架,看起来像这样:

Count  Status
Date                                                                       
2021-01-01  11     1
2021-01-02  13     1
2021-01-03  14     1
2021-01-04  8      0
2021-01-05  8      0
2021-01-06  5      0
2021-01-07  2      0
2021-01-08  6      1
2021-01-09  8      1
2021-01-10  10     0

我想计算"Count"的初始值和最终值之差。"状态"前的列。列从0变为1或反之亦然(对于每个循环),并从这些值生成一个新的数据帧。

这个例子的输出是:

Cycle  Difference
1       3
2      -6
3       2

通过比较移位值与累积和,最后减去最后和第一个值创建的连续组使用GroupBy.agg:

df = (df.groupby(df['Status'].ne(df['Status'].shift()).cumsum().rename('Cycle'))['Count']
.agg(['first','last'])
.eval('last - first')
.reset_index(name='Difference'))
print (df)
Cycle  Difference
0      1           3
1      2          -6
2      3           2
3      4           0

如果需要过滤出组行,1行是可能的,添加聚合GroupBy.size,然后通过DataFrame.loc过滤输出行:

df = (df.groupby(df['Status'].ne(df['Status'].shift()).cumsum().rename('Cycle'))['Count']
.agg(['first','last', 'size'])
.loc[lambda x: x['size'] > 1]
.eval('last - first')
.reset_index(name='Difference'))
print (df)
Cycle  Difference
0      1           3
1      2          -6
2      3           2

您可以对由连续值组成的组使用GroupBy.agg,然后获得第一个减去最后一个值(参见下面的变体):

out = (df.groupby(df['Status'].ne(df['Status'].shift()).cumsum())
['Count'].agg(lambda x: x.iloc[-1]-x.iloc[0])
)

输出:

Status
1    3
2   -6
3    2
4    0
Name: Count, dtype: int64

如果您只想对包含多个元素的组执行此操作:

out = (df.groupby(df['Status'].ne(df['Status'].shift()).cumsum())
['Count'].agg(lambda x: x.iloc[-1]-x.iloc[0] if len(x)>1 else pd.NA)
.dropna()
)

输出:

Status
1     3
2    -6
3     2
Name: Count, dtype: object

作为DataFrame输出:

add.rename_axis('Cycle').reset_index(name='Difference'):

out = (df.groupby(df['Status'].ne(df['Status'].shift()).cumsum())
['Count'].agg(lambda x: x.iloc[-1]-x.iloc[0] if len(x)>1 else pd.NA)
.dropna()
.rename_axis('Cycle').reset_index(name='Difference')
)

输出:

Cycle Difference
0      1          3
1      2         -6
2      3          2

最新更新