首页 > 解决方案 > Pandas:返回值的第一个实例和最后一个实例的索引值

问题描述

我有以下数据框:

df = pd.DataFrame({'index':[0,1,2,3,4,5,6,7,8,9,10], 'X':[0,0,1,1,0,0,1,1,1,0,0]})
df.set_index('index', inplace = True)

   X
index   
0      0
1      0
2      1
3      1
4      0
5      0
6      1
7      1
8      1
9      0
10     0

我需要的是返回一个元组列表,显示每个 1 序列的 1 的第一个和最后一个实例的索引值(对不起,如果这令人困惑)。IE

想:

[(2,3), (6,8)]

第一个 1 的第一个实例出现在索引点 2,然后该序列中的最后一个 1 出现在索引点 3。下一个 1 出现在索引点 6,该序列中的最后一个 1 出现在索引点 8。

我试过的:

我可以使用 numpy 的 argmax 函数来获取第一个。IE

x1 = np.argmax(df.values)
y1 = np.argmin(df.values[x1:])
(x1,2 + y1 - 1)

这会给我第一个元组,但迭代似乎很混乱,我觉得有更好的方法。

标签: pythonpython-3.xpandasdataframe

解决方案


你需要more_itertools.consecutive_groups

import more_itertools as mit
def find_ranges(iterable):
    """Yield range of consecutive numbers."""
    for group in mit.consecutive_groups(iterable):
        group = list(group)
        if len(group) == 1:
            yield group[0]
        else:
            yield group[0], group[-1]
list(find_ranges(df['X'][df['X']==1].index))

输出:

[(2, 3), (6, 8)]

推荐阅读