python - 获取 panda 数据框特定列值连续出现的第一个和最后一个索引

标签 python pandas dataframe

我有一个像这样的数据框,

col1    col2
 4        A
 5        A
 6        B
 7        B
 8        B
 9        A
 10       A
 11       C
 12       C
 13       C
 14       B
 15       B

现在我想获取 B 的每个连续出现的所有开始和停止索引。因此输出将是一个列表,如下列表所示,

[2,4,10,11]  # first continuous B starts at index 2 and ends at index 4, same for 10,11

我可以使用 for 循环通过比较行值来完成此操作,但执行时间会很长。我正在寻找任何 pandas 快捷方式或任何其他方法来最有效地做到这一点。

最佳答案

我会这样做:

isB = df['col2'].eq('B')

# isB.shift() & isB.shift(-1)
# mask those B in the middle
mask = isB & (~(isB.shift() & isB.shift(-1)) )

output = list(df.index[mask])

输出:

[2, 4, 10, 11]

关于python - 获取 panda 数据框特定列值连续出现的第一个和最后一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61965674/

相关文章:

python - 使用 python : openpyxl or any other library 读取 excel 表中单元格的颜色

python - 仅当元素在逗号前有数字时才计算该元素

python - 对特定行应用列减法

python - Pandas 应用于数据框列以返回带有后缀的多列

Python selenium 获取页面标题

python - (discord.py) 如何在 DM 中显示机器人输入指示器

python - 对 csv 文件进行排序 (Python)

python - 在 Pandas 中操作子索引

python - Pandas 使用 UTC 时间创建日期范围

python - 如何在 pandas 数据框中创建包含百分比等的列