【问题标题】:How to Split the pandas column into chunks of n length?如何将 pandas 列拆分为 n 长度的块?
【发布时间】:2020-11-29 22:18:00
【问题描述】:

我正在处理一个大熊猫数据框,它包含两列:

import pandas as pd
df = {'text': ['Expression of H-2 antigenic specificities on', 'To study the distribution of myelin-associated'], 
     'id': [1, 2]}

df = pd.DataFrame(df)

我想检查文本长度是否大于 2,然后将文本分成 2-2 个作品的块,如果长度小于 2,则不要选择取该行。

首先我选择了 len >= 2 的行:

df['len'] = df['text'].apply(lambda x: len(x.split()))
df        = df[df['len']>2].reset_index(drop=True)

现在我想选择将文本分成 2 个单词的块并制作多行,如下所示(这是预期的输出):

                   text  id
0         Expression of   1
1         H-2 antigenic   1
2      specificities on   1
3              To study   2
4      the distribution   2
5  of myelin-associated   2

有explode 方法,但我不知道在使用explode 方法时如何拆分成块?

df['text'] = df['text'].str.split()
df.explode('text')

给出(不是如上预期的输出):

                text  id
0         Expression   1
0                 of   1
0                H-2   1
0          antigenic   1
0      specificities   1
0                 on   1
1                 To   2
1              study   2
1                the   2
1       distribution   2
1                 of   2
1  myelin-associated   2

【问题讨论】:

  • 你的预期输出是什么?
  • @BEN_YO 编辑了问题。

标签: python python-3.x pandas csv


【解决方案1】:

让我们修复您的输出

fixeddf = df.groupby([df['id'], df.groupby('id').cumcount()//2]).agg({'text':' '.join,'id':'first'}).reset_index(drop=True)
Out[270]: 
                   text  id
0         Expression of   1
1         H-2 antigenic   1
2      specificities on   1
3              To study   2
4      the distribution   2
5  of myelin-associated   2

【讨论】:

    【解决方案2】:

    您也可以像现在一样执行explode,首先将字符串分成 2 个块。试试这个 -

    def chunks(s, c):
        return [s[i:i + c] for i in range(0, len(s), c)]
    
    df['text'] = df['text'].apply(lambda x: chunks(x.split(),2))
    df = df.explode('text').reset_index(drop=True)
    df['text'] = df['text'].apply(' '.join, 1)
    
    print(df)
    
                       text  id
    0         Expression of   1
    1         H-2 antigenic   1
    2      specificities on   1
    3              To study   2
    4      the distribution   2
    5  of myelin-associated   2
    

    【讨论】:

      猜你喜欢
      • 2012-07-04
      • 1970-01-01
      • 1970-01-01
      • 2011-01-08
      • 2011-05-05
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多