# Questions tagged [numpy-ndarray]

221 questions

votes
0

answer
14

Views

### Efficient way to calculate matrix cell distance from arbitrary coordinate in numpy

I am looking for an efficient numpy solution to the following problem: I have a N by N numpy matrix. Given an arbitrary i,j coordinate (can be decimal) of the matrix and an arbitrary range, I need to calculate the value of each cell of the matrix divided by its euclidian distance to the coordinate w...
Jakobovski

votes
3

answer
92

Views

### Subtracting minimum of row from the row

I know that a - a.min(axis=0) will subtract the minimum of each column from every element in the column. I want to subtract the minimum in each row from every element in the row. I know that a.min(axis=1) specifies the minimum within a row, but how do I tell the subtraction to go by rows instead...
LeecCL137

votes
4

answer
76

Views

### Increasing the speed of finding an index of an item in list

I'm trying to speed up a program I've written, and after importing cProfile, I see that one function takes up a massive bit of computation time. It's this, which finds an numpy.ndarray in a list: def locate(arr, l ): for i in range(len(l)): if np.all(l[i] == arr): return i return -1 As the list can'...
cucumber

votes
2

answer
150

Views

### Python numpy array negative indexing

I'm a bit confused about the indexing of numpy. Assume the following example: >>> import numpy as np >>> x = np.arange(10) >>> x.shape = (2,5) >>> x array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) >>> x[0:-1] array([[0, 1, 2, 3, 4]]) >>> x[1:-1] array([], shape=(0, 5), dtype=int64) >>> x[1:] array([[5, 6,...
Ragadabing

votes
2

answer
39

Views

### Numpy optimized reshape : 2D array to 3D

I was wondering if there is a more pythonic/efficient way of reshaping my 2d-array into a 3d-array ? Here is the following working code : import numpy as np # # Declaring the dimensions n_ddl = 2 N = 3 n_H = n_ddl*N # # Typical 2D array to reshape x_tilde_2d = np.array([[111,112,121,122,131,132],[21...
Yacola

votes
1

answer
39

Views

### Check if two 3D numpy arrays contain overlapping 2D arrays

I have two very large numpy arrays, which are both 3D. I need to find an efficient way to check if they are overlapping, because turning them both into sets first takes too long. I tried to use another solution I found here for this same problem but for 2D arrays, but I didn't manage to make it work...
Gderu

votes
3

answer
39

Views

### How can I multiply more than 3 vectors at once in NumPy

I'm looking for a vectorised way to multiply more than 3 vectors in NumPy. As an example, X = np.array([1,2,3]) Y = np.array([4,5,6]) Z = np.array([7,8,9]) Multiply([X,Y,Z]) would produce as an output np.array([28, 80, 162]) The vectors I want to multiply need not to be defined separately as I did a...
L. B.

votes
2

answer
54

Views

### how to change a dimension of array in python?

I am a newbie in python. I have a question about the dimension of array. I have (10,192,192,1) array which type is (class 'numpy.ndarray'). I would like to divid this array to 10 separated array like 10 * (1,192,192,1). but I always got (192,192,1) array when I separate. How can I get separated arra...
Tom

votes
0

answer
37

Views

### “ 'numpy.ndarray' object is not callable” error occurs when I get dictionary keys into a list

My dictionay items are as follows, dict_items([(3.0, 0), (2.0, 23), (1.0, 30), (4.0, 41)]) I need to access these dictionary values in terms of the key's index.In order to do that, I used index=list(positions.keys()).pop(0) It renders an error as follows. TypeError: 'numpy.ndarray' object is not cal...
Chamod Pathirana

votes
0

answer
21

Views

### Searching a smaller array in a larger array and returning the indices of larger array

I am working on Feature Selection. I got the selected features but instead of manually searching each time which features are selected, is there any built-in method in python that compare the first row (smaller array) of selected features to the first row of full features(larger array) and return th...
Khan

votes
0

answer
27

Views

### numpy slicing screws image colors (werid)

I have an RGB image as an ndarray print(img.shape) >>> (64, 64, 3) I want to store a bunch of images into another ndarray: batch = np.empty((64, 64, 3, 2)) batch[...,0] = img Now if I do plt.imshow(img) everything is looks fine. But if I do plt.imshow(batch[...,0]) the colors are messed up! It looks...
Nic

votes
0

answer
33

Views

### Size of objects in Numpy Array: Sympy Points example

Here is attached some code in which it is attempted to instantiate a Numpy Array of Sympy Points given their coordinates. from sympy.geometry import Point import numpy as np coordinates = np.array([2,0, 1,-1, 0,0, -2,3, -3,-2, 0.01,-0.01]).reshape(6,2) v1 = np.empty((coordinates.shape[0],),dtype=np...
rauldg

votes
1

answer
38

Views

### What affects tensorlayer.prepro.threading_data's return type?

I've been trying to use tensorlayer.prepro.threading_data, but I'm getting a different return type for different inputs. Sometimes it returns an ndarray and sometimes it returns a list. The documentation doesn't specify what's the reason for the different return types. Can anyone shed some light on...
TomerP

votes
1

answer
834

Views

### ValueError: could not convert string to float: 'lisans' in Python

I am trying to calculate the silhouette index of the output of k-prototypes algorithm to cluster mixed featured dataset. I am getting ValueError: could not convert string to float: 'lisans' as an error, even if my code works fine when I only execute k-prototypes algorithm. My input is an excel file,...
Beg

votes
0

answer
64

Views

### How to define the sampling rate in a 3D numpy array for a multi frame TIFF file?

I have a multi frame TIF file which is a recording of neuronal fluorescence intensity changes over time. The TIF file has 80 x 60 pixels and 2000 frames. I would like to analyse the frequency of the fluorescence intensity changes for each pixel and for that I would need to define the sampling rate o...
Vladi

votes
1

answer
167

Views

### NumPy saving an object with arrays of different shape but same leading dimension

I experienced some unexpected behavior of np.save(). Assume, you want to save two numpy arrays into one .npy file (as an object). As long both arrays have the same shape this works without any problem, but when the leading dimension is the same an error occurs. The problem is caused by np.asanyarray...
Stark

votes
0

answer
54

Views

### Rotate a float ndarray without changing the values

I'd like to rotate a numpy array like this [[0. 0.... 0.771... 0. 0.162 0. ...] [0.987 0.... 0.074 0. 0... 0. ...] [...]] I'm using scipy.ndimage.rotate. Here is my code: matrix = read_mat_file(file_name).reshape((shape[0],shape[1])) matrix_rot = scipy.ndimage.rotate(matrix, angle=60, reshap...
Keira K

votes
0

answer
25

Views

### Numpy, same value inputs get different dot product

I want to get the dot product of matrix X and Adjugate(X) in Python, Numpy, I tried both methods found from here. The adjugate from both method give same answer but when I perform dot product, different answers were given. Here is the code: #first method def CM(A): row, col = A.shape minor = np.zero...
jun kang chin

votes
2

answer
80

Views

### How to merge 2 numpy ndarray on a ndarray using values of a column?

I have 2 ndarray: a = np.array([[1,2], [5,0], [6,4]]) b = np.array([[1,10],[6,30], [5,20]]) I wish merge them in a array as this: [[ 1 2 10] [ 5 0 20] [ 6 4 30]] Someone knows a not iterative mode to merge 2 array by values of column 0? I've found only this way: import numpy as np a = np.array([[...
Stefano G.

votes
1

answer
120

Views

### Multi-dimensional indexing of 4d numpy array

I have two 3d volumes stacked in a 4d array with dimensions 2x5x5x5. If I want to get the values of some/all voxel for a single 3d volume, I can use three vectors and get the following: x_new_mesh, y_new_mesh, z_new_mesh = np.meshgrid(np.arange(m), np.arange(n), np.arange(p)) x_new = x_new_mesh.fl...
Felipe Moser

votes
0

answer
126

Views

### boost::python linking error (undefined reference to numpy::empty and numpy::detail::get_float_dtype<64>()) when using templates

I'm experiencing difficulties working with boost::python and boost::python::numpy, with python 2.7, boost 1.67.0, and Eigen3.3. My compiler is g++ (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0. I'm trying to convert Eigen::Matrix types to python ndarray and back (vector_list.hpp): #ifndef VECTOR_PYLIST_HH...
Kirjain

votes
0

answer
140

Views

### How to convert image in TensorProto in Java

I have written python client for converting my image in TensorProto which I am sending in the predict request. However, I have a need of writing similar client in Java. Below is my python code: def run(): host= 'localhost' port= '9000' request = tensorflow__serving_dot_apis_dot_predict__pb2.Predict...
Yoda

votes
0

answer
49

Views

### overwriting “|” operator to concatenate numpy arrays

I am wondering how to overload/overwrite the | operator to concatenate (two-dimensional) numpy arrays along the second axis, so that u = np.array([[7], [8], [9]]) v = np.array([[1, 2], [3, 4], [5, 6]]) w = u | v produces the same result as u = np.array([[7], [8], [9]]) v = np.array([[1, 2], [3, 4],...
Labrador

votes
0

answer
50

Views

### integral over a cone

Is there a fast way (standard or via some library) to compute integrals over cones in python? I.e. I have an array A containing some values and I want to compute and integral over an index cone specified by numbers in array sliceNums. I can do it directly: n = 10; m=100 # jus...
demitau

votes
1

answer
61

Views

### How to apply an index-dependent function to a numpy ndarray?

So numpy ndarrays are quite handy in that you can just type in f(A) for any one-dimensional function f and any ndarray A and it will apply f element-wise. It is also, I was told, a very efficient way of applying a function to a ndarray and avoiding for loops. Avoid for loops, is what I have been tol...
urquiza

votes
0

answer
23

Views

### Profiling TensorFlow Code to improve efficiency

I’m new to tensorflow. I takes images and returns a preference score for each image, using a pre-trained siamese cnn model. I would like to figure out what parts of my code are expensive. Is there a way to do that with tensorflow or tensorboard? Or does anyone see what parts of my code could b...
user3476463

votes
1

answer
45

Views

### Error when trying to round values in an ndarray

I am working on a memory-based collaborative filtering algorithm. I am building a matrix that I want to write into CSV file that contains three columns: users, app and ratings. fid = fopen('pred_ratings.csv','wt'); for i=1:user_num for j=1:item_num if R(j,i) == 1 entry = Y(j,i); else entry = round(P...
naadiya mirbahar

votes
0

answer
43

Views

### .wav file to numpay array

I am new to python language, i have around 100 of .wav file sample which i want to read from my pc and convert them into numpy-array and gave output of my files. but i can not achieve that until now. So i need help i am following this but i got to know that i just giving irrelevant output because it...
Abdul Rafay

votes
1

answer
35

Views

### Plotting 2darray with matplotlib

a = np.arange(1,10).reshape((3,3)) plt.plot(a[0],a[1:]) Why am I getting: ValueError: x and y must have same first dimension error?
Jasdeep Rana

votes
1

answer
579

Views

### How to convert Tensor to ndarray (tensor with adversarial images inside)

NOTE: I already have tried solutions from different SO questions with no success, details follow. I'm studying cleverhans Pyhton tutorials, focusing on this code (keras model case). I have a base keras knowledge but I've just started with Tensorflow (total newbie). I'm trying to visualize the advers...
Fabiano Tarlao

votes
0

answer
60

Views

### Why does numpy.ndarray's data address change?

I recently ran this in a jupyter notebook (cell), because I wanted to verify memory-address behavior of a numpy array when slicing. The slicing is left out, though, to create a minimal failing example. import numpy as np x = np.zeros(10) x.data.__repr__(), x.data, x.data.__repr__() I was surprised t...
Herbert

votes
2

answer
36

Views

### How to get the exacte value of an np.array?

I have just calculated a probability as an np.array: Proba = [[7.4687206e-10]] but when I compute the complement of this probability, I got: Comp = 1- Proba = [[1.]] The expected value is Comp = [[0.99999999925]] Can any one please, clarify why np.arrays do not give the exact values, and what should...
Nina

votes
1

answer
48

Views

### Masking a multidimensional NumPy array

I want to mask a multidimensional array, say the 4D array A of shape N x N x N x N, where I have a different mask (a, b, and c) for the last three dimension. So a, b, and c are vectors with values True and False of length N. Trying to mask A as A[:,a,b,c] yields an exception (what does this try to d...
Max

votes
0

answer
42

Views

### Peak finding in a 3D noise-free scalar field using Python

I have found multiple questions about peak finding in the forum. However, questions and solutions are almost exclusively only treating the 1D case and usually assume noisy data. I have a 3D field with essentially no noise. I would like to find (i) all the peaks in the field above a certain threshold...
Thomas Möbius

votes
1

answer
41

Views

### getting square and cube of numpy and appending it

I have a numpy array like below :- array([[2], [3], [4], [5]]) I want to square and cube each element and then append it in numpy. and i want the output like below array([[2, 4, 8], [3, 9, 27], [4, 16, 64], [5, 25, 125]])

votes
0

answer
73

Views

### Converting a vti file to a numpy array

I have a 3D geometry (vessels) in vit format which I do not have any information about, but I just visualize it with paraview. I do not know how to read and then convert this vti file to a 3D numpy array in python. Does anyone know how can I do this conversion?
Negar

votes
0

answer
11

Views

### Numpy Array Value Error, looking for specific element in Array

I have loaded an Image of the Array shape (1024, 1152, 3). Then reshaping it into 2D: x, y, z = img.shape img_2d = img.reshape(x*y,z) The second row contains values of the RGB System (e.g. print(img_2d[70000,:]) gives the Output [171 135 115]. I now want to assign each RGB Color Code to one integer...
Luke M.

votes
2

answer
34

Views

### applying array of function to array of elements by position

Assume the following: def x2(x): res=x*x return res def tx(x): res=2*x return res def x3(x): res=x*x*x return res x=np.array([1,2,3]) f=np.array([x2,tx,x3]) Im trying to return an array that is array([x2(1),tx(2),x3(3)]) without using a for loop. Is this possible in python?
Giovanni Baez

votes
1

answer
31

Views

### Numpy: adding n-dimensional vector to m-dimensional vector to get (n, m) matrix

Suppose I have the array [1,2,3,4,5]. I want to 'add' the array [2,4,6,8] to it so I get [[3,5,7,9], [4,6,8,10], [5,7,9,11], [6,8,10,12], [7,9,11,13]] (or its transpose). There is probably a function for this but I can't seem to find it because I'm not sure what to search for.
J. doe

votes
0

answer
57

Views

### how to animate png images using matplotlib with animation.FuncAnimation

I would like to animate an image loaded in python. To load an image, I wrote myrondarray = plt.imread(myimage.png) myrwndarray = myrondarray.copy() So myrwndarray is a RGBA array (x,y,4) I wrote an update function to update myrwndarray, but I'm unable to use with animation.FuncAnimation because it...
MLD