python - 根据出现对数组元素进行分组,保持顺序,获取第一个和最后一个索引

标签 python python-3.x pandas numpy

我想知道 pandas 是否有更好的方法来实现相同的目的:

x = [1, 1, 1, 2, 2, 2, 3, 3, 3, 5, 5, 1, 1, 2, 2]
x = np.asarray(x)

df = pd.DataFrame(columns=['id', 'start', 'end'])

if len(x) > 1:
    i = 0
    for j in range(1, len(x)):
        if x[j] == x[j-1]:
            continue
        else:
            df.loc[len(df)] = [x[i], i, j-1]
            i = j;
    df.loc[len(df)] = [x[i], i, j]
else:
    df.loc[len(df)] = [x[0], 0, 0]

输出看起来像这样

[1 1 1 2 2 2 3 3 3 5 5 1 1 2 2]
  id start end
0  1     0   2
1  2     3   5
2  3     6   8
3  5     9  10
4  1    11  12
5  2    13  14

感谢有用的提示。

最佳答案

您可以使用 numpy 实现此目的:

x = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 5, 5, 1, 1, 2, 2])

# Search for all consecutive non equal values in the array
vals = x[x != np.roll(x, 1)]
# array([1, 2, 3, 5, 1, 2])

# Indices where changes in x occur
d = np.flatnonzero(np.diff(x) != 0)
# array([ 2,  5,  8, 10, 12])

start = np.hstack([0] + [d+1])
# array([ 0,  3,  6,  9, 11, 13])

end = np.hstack([d, len(x)-1])
# array([ 2,  5,  8, 10, 12, 14]) 

pd.DataFrame({'id':vals, 'start':start, 'end':end})

    id  start  end
0   1      0    2
1   2      3    5
2   3      6    8
3   5      9   10
4   1     11   12
5   2     13   14

关于python - 根据出现对数组元素进行分组,保持顺序,获取第一个和最后一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54503566/

相关文章:

python - Nginx 权限被 Django 拒绝 13 静态内容

python - OpenCV BGR 图像转 16 位灰度

python - 如何迭代忽略 "deprecated"的 Python 枚举?

python - 如何从 pandas DataMatrix 获取元数据

python - 在 Pandas 中重新索引和填充 NaN 值

python - 在较小表面内移动表面不会显示以前隐藏的组件

python - 应用程序包中的 PyInstaller Tkinter 窗口分辨率低,但应用程序中没有

python - 删除 Pandas 中的单个和一系列列

python - 在 every/n Python 3 中分解多个列表中的列表条目

Python Pandas 库按截断日期重新采样