gpt4 book ai didi

python - Pandas 根据条件组合连续的行

转载 作者:行者123 更新时间:2023-12-04 17:24:07 24 4
gpt4 key购买 nike

我的问题与这个类似,但答案似乎并不完全有效!!

merge rows pandas dataframe based on condition

给定以下 pandas 数据框:

+---------+-----------------+-----------------+
| SECTION | TEXT | NUMBER_OF_WORDS |
+---------+-----------------+-----------------+
| ONE | lots of text… | 55 |
+---------+-----------------+-----------------+
| ONE | word1 | 1 |
+---------+-----------------+-----------------+
| ONE | lots of text… | 151 |
+---------+-----------------+-----------------+
| ONE | word2 | 1 |
+---------+-----------------+-----------------+
| ONE | word3 | 1 |
+---------+-----------------+-----------------+
| ONE | word4 | 1 |
+---------+-----------------+-----------------+
| TWO | lots of text… | 523 |
+---------+-----------------+-----------------+
| TWO | lots of text… | 123 |
+---------+-----------------+-----------------+
| TWO | word4 | 1 |
+---------+-----------------+-----------------+

如果 NUMBER_OF_WORDS 列中的值为 1;它必须与上面的行结合;前提是它们具有相同的 SECTION 值。

因此最终的结果应该是这样的:

+---------+--------------------------------------+-----------------+
| SECTION | TEXT | NUMBER_OF_WORDS |
+---------+--------------------------------------+-----------------+
| ONE | lots of text…, word1 | 56 |
+---------+--------------------------------------+-----------------+
| ONE | lots of text…, word2, word3, word4 | 154 |
+---------+--------------------------------------+-----------------+
| TWO | lots of text… | 523 |
+---------+--------------------------------------+-----------------+
| TWO | lots of text…, word4 | 124 |
+---------+--------------------------------------+-----------------+

这是代码;这似乎有效,但不是我想要的。

df.groupby(['SECTION', (df.NUMBER_OF_WORDS.shift(1) == 1)], as_index=False, sort=False).agg({'TEXT': lambda x: ', '.join(x), 'NUMBER_OF_WORDS': lambda x: sum(x)})

更新

这是BEN_YO的回答;但他似乎有一个小错字。为了让 future 的用户回答这个问题,我将稍微修改一下他的答案。

s = df['NUMBER_OF_WORDS'].ne(1).cumsum()
out = df.groupby(s).agg({'SECTION': 'first','TEXT': lambda x: ', '.join(x),'NUMBER_OF_WORDS': lambda x: sum(x)})

最佳答案

让我们用 cumsum 试试 groupby

s = df['NUMBER_OF_WORDS'].ne(1).cumsum()
out = df.groupby(s).agg({'SECTION':'first','TEXT':','.join,'NUMBER_OF_WORDS':'sum'})

关于python - Pandas 根据条件组合连续的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64508280/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com