我有一个像这样的数据框,
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/