首页 > 解决方案 > 如何将 pandas 列拆分为 n 长度的块?

问题描述

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

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

标签: pythonpython-3.xpandascsv

解决方案


让我们修复您的输出

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

推荐阅读