python - 根据 Pandas 中的索引范围组合列的行

标签 python pandas list list-comprehension

我有一个包含一列的数据框。

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]

但从这里卡住了。谢谢

最佳答案

通过aSeries.str.contains 比较并按 Series.cumsum 创建群组,然后通过过滤 g[g > 0] 删除可能包含非 a 值的第一组,最后使用 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

关于python - 根据 Pandas 中的索引范围组合列的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59032221/

相关文章:

python - mod_wsgi : ImportError: No module named 'encodings'

python - 比这更好的方法来删除统计异常值?

python pandas dataframe在读取excel文件时添加带有值的列

Python Pandas : Find a pattern in a DataFrame

python - 将值 append 到字典中的一个列表将值 append 到字典中的所有列表

python - '|' 和 '<' 在 numpy 类型中意味着什么?

python - 如何保存通过camera.capture_continuous(格式rgb)读取的图像并将其保存到文件中

indexing - Pandas 数据框 : how to match on multiple index levels when doing arithmetic operations involving two dataframes

python - 对列表进行操作并替换值

python - 删除多个列表元素,知道它们在 python 中的索引