python - 根据熊猫中的索引范围组合列的行
问题描述
我有一个包含一列的数据框。
Index | column1 |
0 and
1 too
2 ask
3 the
4 but
5 hat
6 hot
7 top
8 tap
我想根据条件组合索引之间的行。例如,如果一行有字母“a”,则索引将是:
0, 2, 5, 8
因此,组合行:
(0, 1), (2, 3, 4), (5, 6, 7), (8)
最后的输出是:
Index | column1 |
0 and, too
1 ask, the, but
2 hat, hot, top
3 tap
我尝试过的是:
[i for i in range(len(df['column1'])) if 'a' in df['column1'][i]]
给我指数:
[0, 2, 5, 8]
但从这里卡住了。谢谢
解决方案
比较 bya
并Series.str.contains
创建组 by ,然后通过过滤和最后一个聚合Series.cumsum
删除可能的第一组包含非值:a
g[g > 0]
join
g = df['column1'].str.contains('a').cumsum()
df = df.groupby(g[g > 0])['column1'].apply(', '.join).reset_index(drop=True).to_frame()
print (df)
column1
0 and, too
1 ask, the, but
2 hat, hot, top
3 tap
第一个值不包含a
:
print (df)
column1
1 too
2 ask
3 the
4 but
5 hat
6 hot
7 top
8 tap
g = df['column1'].str.contains('a').cumsum()
df = df.groupby(g[g > 0])['column1'].apply(', '.join).reset_index(drop=True).to_frame()
print (df)
column1
0 ask, the, but
1 hat, hot, top
2 tap
推荐阅读
- c++ - WASAPI 共享模式:音频引擎期望的幅度是多少?
- python - clean() 上的 Django 相关对象空查询集
- c# - 如何在 C# 中将列和行保存到一个变量中?
- javascript - VueJS Axios 谷歌地图 API
- javascript - 三星互联网 CORS 仅发送 OPTIONS 请求
- python - beginner python: my isfile() check stopped working
- html - 用响应式模板中的文本框替换下拉菜单
- angular - How to retrieve/get data from Firebase DB Ionic and Firebase
- java - Kafka consumer poll forever
- android - 在我的 VectorDrawable 图像周围创建细长的矩形边框线