python - 如何将 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
解决方案
让我们修复您的输出
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
推荐阅读
- python - 如何在 TensorFlow Probability 中创建分布数组?
- m2doc - 从 Capella 中提取需求属性
- python - 是否可以在 python 中将其他参数传递给 xgboost 自定义成本函数?
- apache-zookeeper - Zookeeper:客户端的更新是否会导致数据过时?
- reactjs - 日期选择器 - 在今天之前禁用几天不工作
- cuda - 使用 pyCUDA 生成随机数
- dart - 澄清 Dart 中的 mixins 和实现
- spring-boot - Spring Boot - 具有字符串构造函数的自动接线服务
- flutter - 如何基于两个 Firestore 集合构建 Flutter 小部件
- java - 未调用 Spring 注解导入配置