需要在pandas或/和python中保持顺序来分组字母序列

2024-09-23 22:27:27 发布

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

我有一个数据帧:

row1 col1 col2

1    U    1
2    U    1
3    U    1
4    D    1
5    D    1
6    U    1
7    U    1

When I did groupby sum I got :

    col1  col2
1     U     5
2     D     2

But what I want is :

      col1  col2

1       U     3
2       D     2
3       U     2

有人回答了类似的问题。但是使用oraclesql。我只有熊猫和Python。你知道吗

Group rows Keeping the Order of valuesdone with sql

我怎样才能得到输出。你知道吗


Tags: 数据isgroupwhatcol2col1butwhen
1条回答
网友
1楼 · 发布于 2024-09-23 22:27:27

Groupby检查第一行是否不等于第二行。i、 电子

df = pd.DataFrame({'col1':['U','U','D','U','U'],'col2':[3,1,2,1,1]})
mask = df['col1'].ne(df['col1'].shift()).cumsum()
ndf = df.groupby(mask).agg({'col1':'first','col2':'sum'})

     col1  col2
col1           
1       U     4
2       D     2
3       U     2

相关问题 更多 >