Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫索引:标识连续重复相同值的子范围 问题描述_Python_Pandas_Duplicates - Fatal编程技术网

Python 熊猫索引:标识连续重复相同值的子范围 问题描述

Python 熊猫索引:标识连续重复相同值的子范围 问题描述,python,pandas,duplicates,Python,Pandas,Duplicates,我正在寻找一种有效的方法来识别pandasIndex对象中连续重复相同值的所有子范围 示例问题 作为一个简单的例子,考虑下面的代码 索引>代码>对象: import pandas as pd idx = pd.Index(['X', 'C', 'C', 'C', 'Q', 'Q', 'Q', 'Q', 'A', 'P', 'P']) 在此示例中,值C从位置1到3重复,值Q从位置4到7重复,值p从位置9到10重复。然后我试图得到的结果是一个元组列表(或类似的东西),如下所示: [(1, 3, '

我正在寻找一种有效的方法来识别
pandas
Index
对象中连续重复相同值的所有子范围

示例问题

作为一个简单的例子,考虑下面的代码<熊猫> <代码>索引>代码>对象:

import pandas as pd
idx = pd.Index(['X', 'C', 'C', 'C', 'Q', 'Q', 'Q', 'Q', 'A', 'P', 'P'])
在此示例中,值
C
从位置1到3重复,值
Q
从位置4到7重复,值
p
从位置9到10重复。然后我试图得到的结果是一个元组列表(或类似的东西),如下所示:

[(1, 3, 'C'), (4, 7, 'Q'), (9, 10, 'P')]
到目前为止已经试过了 我一直在尝试
pandas.Index.duplicated
属性,但仅此一项,我还未能成功获得预期的结果

编辑: 非常感谢大家的回答。我还有一个后续问题。假设
索引也包含非连续的重复值,如本例所示(其中value
X
多次出现):

如何获得忽略
X
值的结果?即,如何获得本例的以下结果:

[(1, 3, 'C'), (4, 7, 'Q'), (9, 10, 'P')]
这里有一个方法:

In [107]: ix = pd.Series(idx.values)

In [108]: [(v.min(), v.max(),k) for k,v in ix.groupby(ix).groups.items() if len(v) > 1]
Out[108]: [(1, 3, 'C'), (9, 10, 'P'), (4, 7, 'Q')]
原始问题 其中
idx=pd.Index(['X','C','C','Q','Q','Q','A','p','p'])

有点非常规,但应该有效,而且速度似乎也快得多:

# Get a new Index which is the unique duplicated values in `idx`
un = idx[idx.duplicated(keep=False)].unique()

# Call `get_loc` on `idx` for each member of `un` above  
# `np.where` gets position of True in boolean Index
res = []
for i in un:
    w = np.where(idx.get_loc(i))[0]
    # w[0], w[-1] analogous to v.min(), v.max() from @MaxU's answer
    res.append((w[0], w[-1], i))

print(res)
# [(1, 3, 'C'), (4, 7, 'Q'), (9, 10, 'P')]
时间:

%timeit myanswer()
105 µs ± 3.19 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit maxu()
1.21 ms ± 116 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
未注释:

un = idx[idx.duplicated(keep=False)].unique()
res = []
for i in un:
    w = np.where(idx.get_loc(i))[0]
    res.append((w[0], w[-1], i))
编辑问题 其中
idx=pd.Index(['X','C','C','Q','Q','Q','X','p','p'])

要在此处获得
un
,首先获取一个布尔索引,当一个值等于它前面或后面的值时,该索引为True,否则为False。这类似于第一部分中的idx.duplicated(keep=False)

b = (Series(idx).shift() == idx) | (Series(idx).shift(-1) == idx)
un = idx[b].unique()
# Rest should be the same
b = (Series(idx).shift() == idx) | (Series(idx).shift(-1) == idx)
un = idx[b].unique()
# Rest should be the same