Zach
Zach

Reputation: 4744

slice numpy array by column except for 1 row

How can you slice a numpy array by column, and exclude a particular row?

Imagine you have a numpy array where the first column serves as an index as to a 'player', and the next columns are the players scores at different games. How can you return the scores for a game, whilst excluding one player.

For example:

[0  0  0  0
 1  2  1  1 
 2 -6  0  2
 3  4  1  3]

If you want to return the first score (column 1), you would do:

>>score[:,1]
[0,2,-6,4]

But how can you exclude a player/row? If that player/row 3, how do you get:

[0,2,-6]

Or, if that player/row 1, how do you get:

[0,-6, 4]

Upvotes: 3

Views: 7989

Answers (2)

K Z
K Z

Reputation: 30483

You can just pass the players that you want to include as a list to the first index of score like this:

>>> 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])

This will get you only player [0,2,3]'s score.

To generalize, you can do:

>>> 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])

Upvotes: 6

Guy Adini
Guy Adini

Reputation: 5504

You can enter the range of requested rows as a list, for example:

score[ range(2) + [4], 1]

For a more general predicate function p(x) = 1 if x is a good row, you can do:

score [ [x for x in range(score.shape[0]) if p(x)], 1]

Upvotes: 4

Related Questions