How do I create a numpy array with a symmtric range of indices?
I tried:
np.zeros(-100:100,-100:100)
expecting an array with index -100 to +100.
NumPy doesn't have support for this; indexing always starts at zero. You could try writing your own subclass of ndarray, but you'd have a lot of awkward design decisions to make; for example, if you have an array with indices from -100 to 100, where do the indices of array[1:] start and end? And how do you broadcast operations across arrays with compatible shapes, but different indices? What would the bounds be of the result of something like dot?
After some searching I found this. I really didn't need a symmetrical array index. What I wanted was a way to simply specify a circular aperture without an x,y loop. I really don't understand what this ogrid thingy does, but it works.
Cheers,
Gert
import numpy as np
import matplotlib.pyplot as plt
r= 800
s= 1000
y,x = np.ogrid[-s:s+1, -s:s+1]
mask = x*x + y*y <= r*r
aperture = np.ones((2*s+1, 2*s+1))
aperture[mask] = 0
plt.imshow(aperture)
plt.show()
Related
I am trying to come up with a fast way to calculate l2 distance between the rows of two 2d numpy arrays. So first 2d numpy array is 7000 x 100 and second 2d numpy array is 4000 x 100.
I want to get a matrix of 4000 x 7000, where each (i, j) entry is a l2 norm between ith row of second 2d numpy array and jth row of first 2d numpy array.
I am assuming I probably have to use numpy.linalg.norm, but am not quite sure on how to vectorize the operation.
Thanks for the help! Let me know if the question is unclear in any ways.
There is a function in scipy designed specifically for finding all distances between two sets of vectors:
scipy.spatial.distance.cdist(a, b)
I feel like this is a pretty basic question but I can't see to get my head around it. I have a velocity vector V with two components in x and in y that both depend on time. v_x(t) = sin(at) and v_y(t) = exp(bt).
I have created an array for t ranging from 0 to 100 with the function np.arange(0,100,1). I want to plot with matplotlib the resulting vector and its evolution with respect to t. How do I do that?
A simple way that you might try is the following:
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0,100,1)
a = 0.1
b = 0.05
vel = np.array([np.sin(a*t), np.exp(b*t)],float)
plt.plot(vel[0,:],vel[1,:])
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.show()
This gave me the plot
The line vel = np.array([np.sin(a*t), np.exp(b*t)],float) basically does all the magic. np.sin(a*t) makes a new array using each value in t to calculate each element (and np.exp() works similarly).
It would also be possible (and fun) to make an animation of the evolution of the vector.
I have created a 2D 10x10 Array. using Numpy I want to iterate over the array as efficiently as possible.
However I would like to return the array values. essentially iterating over the 10x10 array 10 times and return a 1x10 array each time.
import datetime
import numpy as np
import random
start = datetime.datetime.now()
a = np.random.uniform(low=-1, high=1, size=(10,10))
print("Time :",datetime.datetime.now() - start)
for x in np.nditer(a):
print(x)
the result is as follows:
0.5738994777717537
0.24988408410910767
0.8391827831682657
0.0015975845830569213
0.54477459840569
0.14091622639476165
-0.36517132895234106
-0.06311125453484467
-0.6572544506539948
...
100 times
However I would expect the result to be:
[0.5738994777717537,
0.24988408410910767,
0.8391827831682657,
0.0015975845830569213,
0.54477459840569,
0.14091622639476165,
-0.36517132895234106,
-0.06311125453484467,
-0.6572544506539948],[...]
...
10 times
Any help would be appreciated!
To directly answer your question, this does exactly what you want:
import numpy as np
a = np.random.uniform(low=-1, high=1, size=(10,10))
print(','.join([str(list(x)) for x in a]))
This will print
[-0.2403881196886386, ... , 0.8518165986395723],[-0.2403881196886386, ... , 0.8518165986395723], ..., [-0.2403881196886386, ... , 0.8518165986395723]
The reason you're printing just the elements of the array is due to the way nditer works. nditer iterates over single elements, even at a multidimensional level, whereas you want to iterate over just the first dimension of the array. For that, for x in a: works as intended.
Edit
Here is a good link if you want to read up on how nditer works: https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html#arrays-nditer
I have a image, it's a array. I want to get the value after minimum value, I wish you understand me because I dont speak english very well.
The minimum value in a pixel of this image is -3.40282e+38. I want to know the value that is after -3.40282e+38.
it must be for example 0.3 0.4..
I tried with image.min() but it print -3.40282e+38 .. I need the next value of that.
also I tried
minimo = img.min()
for i in range(rows):
for j in range(cols):
for k in img[i,j]:
if k> minimo:
print k.min()
but I got this error
TypeError: 'numpy.float32' object is not iterable
You can do it like this:
import numpy as np
sorted_vec = np.unique(img.reshape(-1))
second_smallest = sorted_vec[1]
For large arrays, using np.partition will be much faster than sorting the array, as in #dslack's answer:
import numpy as np
img = np.random.rand(1000, 1000)
# Compute via a full sort
np.unique(img.ravel())[1]
# 3.25658401967e-06
# Compute via a partition
np.partition(img.ravel(), 1)[1]
# 3.25658401967e-06
The two methods give the same results, and we can see that the partition approach is significantly faster:
%timeit np.unique(img.ravel())[1]
# 10 loops, best of 3: 86.8 ms per loop
%timeit np.partition(img.ravel(), 1)[1]
# 100 loops, best of 3: 4.99 ms per loop
The reason for the speed is that partition does not sort the full array, but simply swaps values until all smaller values are to the left of the given index, and all larger values are to the right.
Note that the results will differ if the minimum value is not unique – but it is not clear from your question which output you desire in this case.
This is a pretty easy question, I was wondering how to decipher this array:
model[Best[i][j]][6]
Is it recreating another array based off of the 'Best' array within the brackets? I'm not sure how to translate this to myself.
If we are talking about numpy arrays, this will return the value of array model positioned at Best[i][j] (this should be a number perhaps from another array) row and 6th column. Here is an example:
import numpy as np
model = np.array([[1,2],[3,4]])
Best = np.array([[0,0],[1,1]])
i = 0 # Best[i][j] is 0
j = 1
print model[Best[i][j]][1] # It prints model[0][1], which is 2