【问题标题】:python find edge of indexes in a listpython在列表中查找索引的边缘
【发布时间】:2021-04-07 14:58:03
【问题描述】:

我有一个从中过滤值的 DataFrame。假设我的数据是x=[1 1 1 2 2 3 3 3 1 1 1 3 3 1 1];,我想拥有 3 所在的所有索引。所以我正在执行data=df[df.x==3] 来获取列表data.index=[5,6,7,11,12]

现在我想生成一个窄列表,它将为我提供 3 所在的范围: [[5, 7] [11, 12]]。有没有一种简单的方法来做到这一点,而不是为此编写一个函数?

在 Matlab 中,我按照以下方式执行此操作(idx - 3 所在的索引列表,a 是输出)

a(1,1)=idx(1);
j=1;
for i=2:length(idx)
    if (idx(i) ~= (idx(i-1)+1))
        a(j,2)=idx(i-1);
        if i < length(idx)
            j=j+1;
            a(j,1)=idx(i);
        end
    end
end
a(j,2)=idx(end);

【问题讨论】:

  • 我猜你正在寻找“查找序列中所有连续的子序列”;有答案here
  • 我不认为你会在 python 中为Is there a simple way to do it rather than write a function for this 找到现成的模块!
  • “在一个序列中找到所有连续的子序列”——这就是想法。但链接有点其他问题

标签: python dataframe


【解决方案1】:

您使用的是 Python 3 吗?我不知道你说的简单是什么意思。

如果你有数据列表 -> data = [5,6,7,11,12]

你可以这样分组(参考 Python 文档HERE

from itertools import groupby
from operator import itemgetter

ranges =[]
data = [5,6,7,11,12]
for k, g in groupby(enumerate(data), lambda x:x[0]-x[1]):
    group = list(map(itemgetter(1), g))
    ranges.append([group[0], group[-1]])
print(ranges)

给你,

[[5, 7], [11, 12]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 2020-12-05
    相关资源
    最近更新 更多