# Questions tagged [numpy-ndarray]

207 questions

1

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...

1

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...

1

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...

1

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...

1

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([[...

1

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...

1

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...

1

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...

1

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],...

1

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...

1

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...

1

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...

1

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...

1

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...

1

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?

1

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...

1

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...

1

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...

1

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...

1

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...

1

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]])

1

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?

1

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...

1

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?

1

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.

1

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...

1

votes

0

answer

194

Views

### Append a nd numpy array into existing csv file

I have a csv file and i tried to append to it a numpy array with the shape (1,538,341).
I have tried 2 different approches :
1) convert the np to pandas and then save it to the csv.
2) use of the np.totext
in both cases I got an error
can someone help me?
thanks in advance

1

votes

2

answer

72

Views

### Applying a mapping function to each member of an ndarray with indices as arguments

I have an ndarray representing an RGB image with the shape of (width,height,3) and I wish to replace each value with the result of some function of itself, its position and the color channel it belongs to. Doing so in three nested for loops is extremely slow, is there a way to express this as a nati...

1

votes

2

answer

71

Views

### remove duplicate 2D numpy.array

I want to remove some 'duplicate' items in below array:
arr = array([[1, 2, 3, 0, 1],
[0, 0, 0, 1, 0]])
In the above array, arr[:, 0], arr[:, 3] and arr[:, 4] should be seen as duplicates. And finally, I want this result:
arr = array([[1, 2, 3],
[0, 0, 0]])

1

votes

0

answer

17

Views

### In python, how do I combine two np arrays with similar but not exactly same shape

How do you combine two np arrays b.shape (10000,28,28,1) to the end of a.shape (60000,28,28,1) so that the result is c.shape (70000,28,28,1)?
someone suggested to use np.stack((a,b),axis=0) but I’m getting the following ValueError: all input arrays must have the same shape. please advise.

1

votes

0

answer

32

Views

### Created ndarray from a .mat file, but how to format for a pandas dataframe?

I am loading data from a MATLAB .mat file into python. The .mat file has a number of cells, and within each cell is a struct with several named fields:
samp = 1x2 cell array
{1×1 struct} {1×1 struct}
samp{1}.buttonID = 3
samp{1}.buttonName = 'name3'
I have loaded the .mat file into python using...

1

votes

0

answer

272

Views

### IndexError : arrays used as indices must be Integers (or boolean) type

Background
I have 4 Numpy 1 D arrays of length 107952899.
I combine the above 1d as multi D array & Transpose them of order (107952899, 4) and stored it data1.
I set column names for my array. (e.g : data1[:, 0] = Index)
(Like above, 0th col - Index, 1st- Time, 2nd- Speed, 3rd col - Brake)
I followe...

1

votes

1

answer

27

Views

### Build 3D array from subarrays generated by meshgrid and introduce a 3th dimension

I am new to python and I would like to build a full 3D array with dimensions = 1e3 x 1e3 x 16.
For this, I tried to do :
dimBlocks = 4
numElBlock = 1000
numPoints = 1000
arrayCrossX = np.linspace(kMIN, kMAX, numPoints, endpoint=True)
arrayCrossY = np.linspace(-1, 1, numPoints, endpoint=True)
coordCr...

1

votes

1

answer

44

Views

### How to get a value of numpy ndarray at index or NaN for IndexError?

My question is similar to this one
Get value at list/array index or 'None' if out of range in Python
but I want to use multidimensional numpy array.
Can this be done without checking the indexes beforehand?
data = np.ones((2,3,4))
idx1 = [0,1]
idx2 = [1,2]
idx3 = [0, 100]
data[idx1, idx2, idx3]
Des...

1

votes

0

answer

87

Views

### Why are 3D numpy arrays printed the way they are?

I am trying to wrap my head around 3D arrays (or multi-dimensional arrays in general), but it's blowing my brains a bit. Especially the way in which 3D numpy arrays are printed is counter-intuitive to me. This question is similar but it is more about the differences between programming languages, an...

1

votes

2

answer

50

Views

### Changing individual elements of numpy array based on its value

I'm trying to iterate over every element of an numpy array and change its value in a semi-random manner. The reason for that is, that I'll apply that method to different arrays: I want them to be changed but I don't want them to be changed the same way.
Here is what I tried so far:
with np.nditer(sm...

1

votes

2

answer

35

Views

### Python Concatenate and stack many matrices [duplicate]

This question already has an answer here:
Toeplitz matrix of toeplitz matrix
2 answers
I want to create a square matrix like this one where its element is a square matrix either the B square matrix or the negative identity matrix or zeros. I have created the B matrix as well as the -I and also I ha...

1

votes

1

answer

27

Views

### Euclidean distance: results are different between python and numpy with large number of instances

I am trying two methods to implement the square result of euclidean distance.
By Numpy:
def inference(feature_list):
distances = np.zeros(len(feature_list))
for idx, pair in enumerate(feature_list):
distances[idx] = euclidean_distances(pair[0].reshape((1, -1)), pair[1].reshape((1, -1))).item()
dista...

1

votes

1

answer

25

Views

### Numpy tensor implementation slower than loop

I have two functions that compute the same metric. One ends up using a list comprehension to cycle through a calculation, the other uses only numpy tensor operations. The functions take in a (N, 3) array, where N is the number of points in 3D space. When N ~ 3000 the list comprehension is faster. Bo...

1

votes

1

answer

15

Views

### Rearranging the rows in the numpy and keeping track of each row

I have a 2000 numpy arrays of size 7 x 11. The rows are arranged in the following order of variables: pi, Tajima's D, Theta, dust kurtosis, J1/J2, J1, J2. That is first row always corresponds to pi, second row corresponds to Tajima's D and so on.
What I want to do is shuffle the rows but also keepin...