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
How to Jump to a Particular Line in a Huge Text File
Plot a Horizontal Line on a Given Plot
Elegant Python Code for Integer Partitioning
How to Un-Escape a Backslash-Escaped String
How to Create a Custom String Representation for a Class Object
How Slow Is Python's String Concatenation VS. Str.Join
How to Get Text with Selenium Webdriver in Python
Printing List Elements on Separate Lines in Python
How to .Decode('String-Escape') in Python 3
How to Check If the String Is Empty
Is There a List of Pytz Timezones
How to Convert JSON Data into a Python Object
How to Delete a Character from a String Using Python
How to Capitalize the First Letter of Each Word in a String