按行切片numpy数组除1行外

Zac*_*ach 2 python arrays numpy

如何按列切割numpy数组,并排除特定行?

想象一下,你有一个numpy数组,其中第一列作为"玩家"的索引,接下来的列是不同游戏中的玩家得分.如何排除游戏的分数,同时排除一名玩家.

例如:

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

如果你想返回第一个分数(第1列),你会这样做:

>>score[:,1]
[0,2,-6,4]
Run Code Online (Sandbox Code Playgroud)

但是如何排除玩家/排?如果那个玩家/第3行,你怎么得到:

[0,2,-6]
Run Code Online (Sandbox Code Playgroud)

或者,如果该玩家/第1行,你如何得到:

[0,-6, 4]
Run Code Online (Sandbox Code Playgroud)

K Z*_*K Z 6

您可以将要包含的播放器作为列表传递到第一个索引,score如下所示:

>>> import numpy as np
>>> score = np.array([
... [0,0,0,0],
... [1,2,1,1],
... [2,-6,0,2],
... [3,4,1,3]
... ])
>>> players_to_include = [0,2,3]
>>> score[players_to_include, 1]
array([ 0, -6,  4])
Run Code Online (Sandbox Code Playgroud)

这将只获得玩家[0,2,3]的分数.

概括来说,你可以这样做:

>>> players = list(xrange(np.size(score, 0)))
>>> players
[0, 1, 2, 3]
>>> excludes = [2,3]
>>> players_to_include = [p for p in players if p not in excludes]
>>> players_to_include
[0, 1]
>>> score[players_to_include, 1]
array([0, 2])
Run Code Online (Sandbox Code Playgroud)