【问题标题】:pandas: concat rows of strings until specifc characterspandas:连接字符串行直到特定字符
【发布时间】:2018-06-30 23:32:11
【问题描述】:

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

   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. &,,

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

【问题讨论】:

    标签: python string pandas dataframe


    【解决方案1】:

    您可以在分隔符上joinsplit 重新创建数据框:

    df = pd.DataFrame(
        ''.join(df.Words.values)
        .split('&,,'), columns=['Words']
    )
    
                                                   Words
    0                                      hello world!
    1  I woke up this morning and made some eggs.They...
    2
    

    如果最后一列&,, 结尾,这可能会导致空值,但过滤这些行很容易:

    df.loc[df.Words.ne('')]
    
                                                   Words
    0                                      hello world!
    1  I woke up this morning and made some eggs.They...
    

    【讨论】:

      【解决方案2】:

      您可以使用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. &,,
      

      【讨论】:

        猜你喜欢
        • 2018-05-27
        • 1970-01-01
        • 2017-05-21
        • 2014-11-25
        • 2014-06-28
        • 2017-01-10
        • 2014-03-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多