How to Access the Ith Column of a Numpy Multidimensional Array

How do I access the ith column of a NumPy multidimensional array?

To access column 0:

>>> test[:, 0]
array([1, 3, 5])

To access row 0:

>>> test[0, :]
array([1, 2])

This is covered in Section 1.4 (Indexing) of the NumPy reference. This is quick, at least in my experience. It's certainly much quicker than accessing each element in a loop.

Extracting specific columns in numpy array

I assume you wanted columns 1 and 9?

To select multiple columns at once, use

X = data[:, [1, 9]]

To select one at a time, use

x, y = data[:, 1], data[:, 9]

With names:

data[:, ['Column Name1','Column Name2']]

You can get the names from data.dtype.names

How to access specific row of multidimensional NumPy array with different dimension?

It does not make sense to have different number of elements in different rows of a same matrix. To work around your problem, it is better to first fill all the missing elements in rows with 0 or NA so that number of elements in all rows are equal.

Please also look at answers in Numpy: Fix array with rows of different lengths by filling the empty elements with zeros. I am implementing one of the best solutions mentioned there for your problem.

import numpy as np
def numpy_fillna(data):

lens = np.array([len(i) for i in data])
mask = np.arange(lens.max()) < lens[:,None]

out = np.zeros(mask.shape, dtype=data.dtype)
out[mask] = np.concatenate(data)
return out

a =np.array([range(1,50),range(50,150)])
data=numpy_fillna(a)

print data[1,:]

Extracting multiple sets of rows/ columns from a 2D numpy array

IIUC, you can use numpy.r_ to generate the indices from the slice:

img[np.r_[0,2:4][:,None],2] 

output:

array([[ 2],
[12],
[17]])

intermediates:

np.r_[0,2:4]
# array([0, 2, 3])

np.r_[0,2:4][:,None] # variant: np.c_[np.r_[0,2:4]]
# array([[0],
# [2],
# [3]])

How to use NumPy to sort a multidimensional array from highest to lowest value

import numpy as np
X = np.array([['Larry', '90%'], ['Beth', '100%'], ['Arnold', '90%']])
X[np.array([-float(num.strip('%'))/100 for num in X[:, 1]]).argsort()]

Slice multidimensional numpy array from max in a given axis

As @hpaulj mentionned in the comments, using a[wheremax, np.arange(m)] did the trick.



Related Topics



Leave a reply



Submit