python - 合并 Pandas 中的连续行并保留一些行不变

标签 python pandas dataframe

我已经尝试查看 pandas 解决方案中的其他合并行 herehere尤其是解决方案here .

我想将从项目符号点中抓取的单个句子组合成一个段落介于空白行。但是保持空白行原样。我想将第一句的段落 ID 保留为新 ID。 (段落 id 不一定是连续的,因为已经进行了一些预清理。)

df = pd.DataFrame(data = [[1, "A Heading"],
                          [2, "I need to be with above."],
                          [3, ""],
                          [8, "I stand alone."],
                          [9, ""]],columns=['para_id','text'])

df   
# The data
#    para_id                      text
# 0        1                 A Heading
# 1        2  I need to be with above.
# 2        3                          
# 3        8            I stand alone.
# 4        9                         

我需要的输出是:

#    para_id                                    text
# 0        1  A Heading. I need to be with above
# 1        3  
# 2        8  I stand alone.
# 3        9   

在答案的帮助下,我已经很接近了,只需要多一点指导。

尝试的解决方案

df['t'] =  df['text'].str.len().values
s = df['t'].eq(0).cumsum()
out = df.groupby(s).agg({'para_id': 'first',
                         'text': lambda x: '. '.join(x),
                         't': 'last'})
out.drop('t', inplace=True, axis=1)
   
out
# Incorrect output
#    para_id                                 text
# t                                              
# 0        1  A Heading. I need to be with above.
# 1        3                     . I stand alone.
# 2        9

我几乎可以正常工作了,但是我的空白行粘在了一些文本上。所以我错过了我的第一个空白行。

  1. 请有人帮助我更好地制定 s 以获得所需的输出。

  2. 我也需要加盟。只有在最后一句话末尾没有句号的情况下才会发生。 (这并不重要。我想我可以先在非空文本句子的末尾搜索缺失的句号,然后加入句子,但我想知道 pandas 中是否有 mutate if 类型的结构.)

最佳答案

你快到了,只需对非零长度和 cumsum 进行分组:

s = df['text'].eq('')

(df.groupby([s.cumsum(),s], sort=False)
   .agg({'para_id':'first', 'text': '. '.join})
   .reset_index(drop=True)
)

输出:

   para_id                                 text
0        1  A Heading. I need to be with above.
1        3                                     
2        8                       I stand alone.
3        9                                     

关于python - 合并 Pandas 中的连续行并保留一些行不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70113828/

相关文章:

python - 在 pandas/python 中嵌套带有 .loc 的 if 语句

python - 使用 datetime64 进行 numpy 数字化

python - 避免 FOR 循环将多个字符串 append 到列表

python - 在现有的 sql 表中创建新列,使用 pandas Dataframe 中的额外列

Java 生产者、Stompy Python 消费者、ActiveMQ

python - 如何在 Google App Engine 中正确保存表单数据

python - 递归列表函数

具有大/无序文本文件的 Python-pandas

python-3.x - 在子图中绘制不同的数据帧数据

python - 连接和排序表未按预期工作