首页 > 解决方案 > pandas:连接字符串行直到特定字符

问题描述

我有一个单列数据框。该列的行包含通常跨越多行的对话。每个人对话行的末尾都是相同的字符“&,”组合,如下所示:

   Words
1  hello world! &,,
2  I woke up this morning and made some eggs.
3  They tasted good. &,,

我想将不以“&,”结尾的每一行与下一行合并,这样每一行都是一个不同的人在说话,而不是同一段落的多行。它看起来像这样:

   Words
1  hello world! &,,
2  I woke up this morning and made some eggs. They tasted good. &,,

我看到的每个与此类似的问题都涉及另一列,该列将指定一些额外的信息,例如,它可能会说谁在说话,但是对于这个数据集,我没有那个,我也没有另一个包含更多信息的数据集,所有我有的是分隔符。

标签: pythonstringpandasdataframe

解决方案


您可以使用df['Words'].str.endswith('&,,')来查找以 结尾的行&,,,然后用于cumsum生成所需的组号(存储在下面的row列中)。获得这些组编号后,您可以使用pd.pivot_table将 DataFrame 重塑为所需的形式:

import sys
import pandas as pd
pd.options.display.max_colwidth = sys.maxsize

df = pd.DataFrame({
   'Words': ['hello world! &,,',
             'I woke up this morning and made some eggs.',
             'They tasted good. &,,']}, index=[1, 2, 3])

df['row'] = df['Words'].str.endswith('&,,').shift().fillna(0).cumsum() + 1
result = pd.pivot_table(df, index='row', values='Words', aggfunc=' '.join)
print(result)

产量

                                                                Words
row                                                                  
1                                                    hello world! &,,
2    I woke up this morning and made some eggs. They tasted good. &,,

推荐阅读