I can't for the life of me figure this out.
I'm trying to remove every other element in the second axis of an array. I did this in MATLAB with arr(:,:,2:2:end) = [];, but when I tried to do the same in Python and compare the two outputs, I get a different matrix.
I've tried arr = np.delete(arr,np.arange(0,arr.shape[2],2),2) and arr = arr[:,:,1::2], but neither seem to come up with something I get with MATLAB.
Example:
MATLAB
disp(['before: ',str(arr[21,32,11])])
arr(:,:,2:2:end) = [];
disp(['after: ',str(arr[21,32,11])])
output:
before: 99089
after: 65699
Python
print 'before: ' + str(arr[20,31,10])
arr = arr[:,:,1::2] # same output as np.delete(arr,np.arange(0,arr.shape[2],2),2)
print 'after: ' + str(arr[20,31,10])
output:
before: 99089
after: 62360
I hope I'm not overlooking something fundamental.
You are trying to delete every other element starting from the second element onwards in the last axis. In other words, you are trying to keep every other element starting from the first element onwards in that axis.
Thus, working the other way around of selecting elements instead of deleting elements, the MATLAB code arr(:,:,2:2:end) = [] would be equivalent to (neglecting the performance numbers) :
arr = arr(:,:,1:2:end)
In Python/NumPy, this would be:
arr = arr[:,:,0::2]
Or simply:
arr = arr[:,:,::2]
Related
Hi have an original vector, I would like to put the first 3 elements into new vector, do some math and then get new elements after the math. Put those new elements into a new vector, delete the original first 3 elements from original vector and repeat this exact procedure until the original vector is empty.
This is what I have done so far
OR=np.array([1,2,3,4,5,6])
new=OR[0:3]
while (True):
tran=-2*c_[new]
OR= delete(OR, [0,1,2])
new=OR[0:3]
if (OR==[]):
break
However it is not working out properly, do you have any suggestions?
Not sure what c_ is in your code, but regardless since numpy arrays are not dynamic, you can't remove or add elements to them. Deleting elements creates a new array without those elements, which is not optimal. I think you should either use a python deque which has fast pop methods for removing one element from the front/end, or just iterate over the original numpy array, for example like this:
def modify_array(arr):
# your code for modifying the array here
result = []
original_array = np.arange(1, 10)
for idx in range(0, len(original_array), 3):
result.append(modify_array(original_array[idx:idx+3]))
result = np.concatenate(result)
Let's say I have a really long array like this:
arr = np.array([0,0,1,1,0,1,1,1,0,0,0,1,1,0,0,1]}
I also have a maximum position where I can look, like 6, making a slice of the array that returns this:
sliceLocation = 6
returning:
np.array([0,0,1,1,0,1,1]}
now I want to write a piece of code that slices the array and then searches for the first 0 inside this array coming from the back, in this case returning 4 as a viable position in a quick and efficient time. Can anybody help me?
Here is your example but i dont understand what you want to do with the rest of the array arr.
arr = np.array([0,0,1,1,0,1,1,1,0,0,0,1,1,0,0,1])
sliceLocation = 6
arr = arr[:sliceLocation+1]
idx = np.where(arr==0)[0][-1]
idx = 4
The following should work:
sliceLocation = 6
sliceLocation-list(arr)[:sliceLocation+1][::-1].index(0)
4
How it works: It slices the array, changes it to a list, reverses it, find the index of first 0 and by subtracting it from sliceLocation it gives the final result
I want to slice 3D arrays in a way to only print the last element of each row in the 2nd array.
In my 3D Array:
np.random.seed(42)
M = np.random.randint(10, size=(2,2,10))
print(M)
I tried accessing the last elements of the 2nd Array in a way like this:
print(M[1::2]) ## which just prints me the whole 2nd Array
print(M[1::,2]) ## which gives me an error of index 2 being out of bounds
I understand the first print() method like:
1: # chose the second array
: # chose all rows of the 2nd array
:2 # chose every second index of the row and print it
strangely it prints the whole array which confuses me.
The second print() method i was hoping to at least print the 2nd index alone but I get that error message.
So I tried around more and came up with that code:
print(M[1:,0:,::2])
It gives me the result I want, but I cannot read the code.
I understand
1: ## which chooses the 2nd array
but ,0:,::2 is confusing me. ::2 is chosing every 2nd index I guess but I still don't understand when I can make ':' and when not. Or what is the meaning of ',' in the slicing process.
In numpy,the operator works as follows :- [start_index:end_index:step].
This means that when you index M[1:,0:,::2] what you are actually indexing is everything from the first index of the first dimension([1:]), then everything from the start of the second dimension([0:]), and finally every element with a step of 2 ([::2]).
The , is used to seperate the dimensions so I assume what you actually want to do is M[:,1,-1] to get the last element of every 2nd array.
Suppose I have a list of list called mat of shape 5x5.
Then I initialize a "column", element by element as follows
mat[0][4] = 'X'
mat[1][4] = 'O'
mat[2][4] = 'R'
mat[3][4] = 'N'
mat[4][4] = 'A'
Is there any way to initialize this column vector in one line in Python like how MATLAB might do?
mat[:,4] = ['X','O','R','N','A']
Not quite as concise, but:
for i,x in enumerate(['X','O','R','N','A']): mat[i][4]=x
Or in the case of single characters, slightly shorter:
for i,x in enumerate('XORNA'): mat[i][4]=x
Alternatively, you can use numpy:
import numpy
mat=numpy.array([[' ' for i in range(5)] for j in range(5)])
mat[:,4] = ['X','O','R','N','A']
I had a similar problem a couple of years ago while developing a Sudoku algorithm. I had to frequently switch between columns and rows and the nested "for" where killing me.
So I came up with the easy solution to just rotate my matrix and always treat everything as a row. If optimisation is not an issue, you can do that.
Here is how to rotate a multi-dimensional array in python: Rotating a two-dimensional array in Python
I have created an array in the way shown below; which represents 3 pairs of co-ordinates. My issue is I don't seem to be able to find the index of a particular pair of co-ordinates within the array.
import numpy as np
R = np.random.uniform(size=(3,2))
R
Out[5]:
array([[ 0.57150157, 0.46611662],
[ 0.37897719, 0.77653461],
[ 0.73994281, 0.7816987 ]])
R.index([ 0.57150157, 0.46611662])
The following is returned:
AttributeError: 'numpy.ndarray' object has no attribute 'index'
The reason I'm trying to do this is so I can extend a list, with the index of a co-ordinate pair, within a for-loop.
e.g.
v = []
for A in R:
v.append(R.index(A))
I'm just not sure why the index function isn't working, and can't seem to find a way around it.
I'm new to programming so excuse me if this seems like nonsense.
index() is a method of the type list, not of numpy.array. Try:
R.tolist().index(x)
Where x is, for example, the third entry of R. This first convert your array into a list, then you can use index ;)
You can achieve the desired result by converting your inner arrays (the coordinates) to tuples.
R = map(lambda x: (x), R);
And then you can find the index of a tuple using R.index((number1, number2));
Hope this helps!
[Edit] To explain what's going on in the code above, the map function goes through (iterates) the items in the array R, and for each one replaces it with the return result of the lambda function.
So it's equivalent to something along these lines:
def someFunction(x):
return (x)
for x in range(0, len(R)):
R[x] = someFunction(R[x])
So it takes each item and does something to it, putting it back in the list. I realized that it may not actually do what I thought it did (returning (x) doesn't seem to change a regular array to a tuple), but it does help your situation because I think by iterating through it python might create a regular array out of the numpy array.
To actually convert to a tuple, the following code should work
R = map(tuple, R)
(credits to https://stackoverflow.com/a/10016379/2612012)
Numpy arrays don't an index function, for a number of reasons. However, I think you're wanting something different.
For example, the code you mentioned:
v = []
for A in R:
v.append(R.index(A))
Would just be (assuming R has unique rows, for the moment):
v = range(len(R))
However, I think you might be wanting the built-in function enumerate. E.g.
for i, row in enumerate(R):
# Presumably you're doing something else with "row"...
v.append(i)
For example, let's say we wanted to know the indies where the sum of each row was greater than 1.
One way to do this would be:
v = []
for i, row in enumerate(R)
if sum(row) > 1:
v.append(i)
However, numpy also provides other ways of doing this, if you're working with numpy arrays. For example, the equivalent to the code above would be:
v, = np.where(R.sum(axis=1) > 1)
If you're just getting started with python, focus on understanding the first example before worry too much about the best way to do things with numpy. Just be aware that numpy arrays behave very differently than lists.