小编luk*_*uki的帖子

如何对 numpy ndarray 进行分组并从每个组返回第一行。现在排序之前

我有 ndarray:

[[1 1]
 [0 2]
 [0 3]
 [1 4]
 [1 5]
 [0 6]
 [1 7]]
Run Code Online (Sandbox Code Playgroud)

我期望这样的减少结果:

[[1 1]
  [0 2]
  [1 4]
  [0 6]
  [1 7]]
Run Code Online (Sandbox Code Playgroud)

结果 ndarray 应包含每组的第一行。我根据第 0 列中的值构建一个组。这是值 0 或 1。

类似的问题在线程中得到解决:Is there any numpy group by function? 但钥匙已排序,在我的情况下它不起作用。

l1 = [1,0,0,1,1,0,1]
l2 = [1,2,3,4,5,6,7]
a = np.array([l1, l2]).T
print(a)
values, indexes = np.unique(a[:, 0], return_index=True)
Run Code Online (Sandbox Code Playgroud)

在 pandas 中,我们可以通过(来自堆栈的解决方案,但我不记得所有者,抱歉没有链接)来实现这一点:

m1 = ( df['c0'] != df['c0'].shift(1)).cumsum()
df = df.groupby([df['c0'], m1]).head(1)
Run Code Online (Sandbox Code Playgroud)

如何用numpy制作它?

谢谢您的解决方案。

编辑:

当 mozway 编写解决方案时,我创建了类似的东西: …

python numpy pandas

1
推荐指数
1
解决办法
173
查看次数

标签 统计

numpy ×1

pandas ×1

python ×1