I have a big numpy array and want to take the mean of the second columns of each two rows and save the array as a new one. I want to take the mean of each two row, i.e. the mean of second column of of rows 1 and 2. Then, mean of second column of rows 3 and 4, and so on. Then, I want to merge each two rows as a single one. First and third columns of this paired rows are also the same. This is my simplified array:
input= np.array ([[1., 2., 5.],
[1., 4., 5.],
[4., 10., 3.],
[4., 2., 3.],
[1., 0., 0.],
[1., 1., 0.]])
Then, I want to get:
output= np.array ([[1., 3., 5.],
[4., 6., 3.],
[1., 0.5, 0.]])
I tried the following but it was not successful at all:
output=np.array([])
for i in range (len(input)-1):
g=(input[i,1]+input[i+1,1])/2
output=np.append(g,output)
In advance, I do appreciate any help.
For two rows, I find it easier to do:
(arr[::2] + arr[1::2])/2
A little more robust method for reshape, using the input shape
i= np.array ([[1., 2., 5.],
[1., 4., 5.],
[4., 10., 3.],
[4., 2., 3.],
[1., 0., 0.],
[1., 1., 0.]])
i.reshape(-1, 2, i.shape[-1]).mean(1)
array([[1. , 3. , 5. ],
[4. , 6. , 3. ],
[1. , 0.5, 0. ]])
You could reshape and find the mean, as follows:
import numpy as np
ipt = np.array([[1., 2., 5.],
[1., 4., 5.],
[4., 10., 3.],
[4., 2., 3.],
[1., 0., 0.],
[1., 1., 0.]])
result = np.mean(ipt.reshape((3, 2, 3)), axis=1)
print(result)
Output
[[1. 3. 5. ]
[4. 6. 3. ]
[1. 0.5 0. ]]
As a side note, avoid using input as a variable name as it shadows the built-in input.
Take even rows (ipt[::2]), odd rows (ipt[1::2]), add them and divide by 2:
output = (ipt[::2] + ipt[1::2])/2
Related
I have a list of numpy arrays and want to modify some numbers of arrays. This is my simplified list:
first_list=[np.array([[1.,2.,0.], [2.,1.,0.], [6.,8.,3.], [8.,9.,7.]]),
np.array([[1.,0.,2.], [0.,0.,2.], [5.,5.,1.], [0.,6.,2.]])]
I have a factor which defines how many splits I have in each arrays:
spl_array=2.
it means each array of the list can be splited into 2 ones. I want to add a fixed value (3.) into last column of each split of each array and also copy the last split and subtract this value (3.) from the third column of this copied split. Finally I want to have it as following:
final_list=[np.array([[1.,2.,3.], [2.,1.,3.], [6.,8.,6.], [8.,9.,10.], \
[6.,8.,0.], [8.,9.,4.]]), # copied and subtracted
np.array([[1.,0.,5.], [0.,0.,5.], [5.,5.,4.], [0.,6.,5.], \
[5.,5.,-2.], [0.,6.,-1.]])] # copied and subtracted
I tried some for loops but I totaly lost. In advance , I do appreciate any help.
final_list=[]
for i in first_list:
each_lay=np.split (i, spl_array)
for j in range (len(each_lay)):
final_list.append([each_lay[j][:,0], each_lay[j][:,1], each_lay[j][:,2]+3])
Is it what you expect:
m = np.asarray(first_list)
m = np.concatenate((m, m[:, 2:]), axis=1)
m[:, :4, 2] += 3
m[:, 4:, 2] -= 3
final_list = m.tolist()
>>> m
array([[[ 1., 2., 3.],
[ 2., 1., 3.],
[ 6., 8., 6.],
[ 8., 9., 10.],
[ 6., 8., 0.],
[ 8., 9., 4.]],
[[ 1., 0., 5.],
[ 0., 0., 5.],
[ 5., 5., 4.],
[ 0., 6., 5.],
[ 5., 5., -2.],
[ 0., 6., -1.]]])
I want to rearrange NumPy arrays stored as list. I want to replace the rows that their second column is the same as the previous row. I case of having similar second rows in each array, I want to replace the second one by increasing their indices using a defined number. This is my simplified list (I purposefully showed the third column by alternative positive and negative numbers, in reality they are all positive):
old_points = [np.array([[2., 0., 9.8],
[2., 0., -4.1],
[2., 1., 9.9],
[2., 1., -4.],
[2., 2., 9.],
[2., 2., -4.],
[3., 0., -4.1],
[3., 1., -4.],
[3., 2., -4.9]]),
np.array([[1., 0., 20.],
[1., 0., -3.],
[1., 1., 22.2],
[1., 1., -3.8]])]
For the first array of old_points I want to add 2 to the index of the similar row, then add 1 and finally add 0. I mean second row of first array ([2., 0., -4.1]) will become fourth of new one, the fourth ([2., 1., -4.]) will become the fifth in new one (increase of the indices decrease linearly by 1, because our arrays has lost its second row) and finally the third row which is similar to its upper row ([2., 2., -4.]) will remain there with 0 movement. For the second array I want to move the first similar row ([1., 0., -3.]) one step ahead (from old_points[1][1] to new_points[1][2]). The last similar row again will change with 0 movement (i.e. remains in the same position).
new_points = [np.array([[2., 0., 9.8],
[2., 1., 9.9],
[2., 2., 9.],
[2., 0., -4.1],
[2., 1., -4.],
[2., 2., -4.],
[3., 0., -4.1],
[3., 1., -4.],
[3., 2., -4.9]]),
np.array([[1., 0., 20.],
[1., 1., 22.2],
[1., 0., -3.],
[1., 1., -3.8]])]
In advance, I do appreciate any help and contribution.
The following function rearranges an array in the way you described through NumPy's advanced indexing:
def rearrange(arr):
n_rows = arr.shape[0]
all_rows = np.arange(n_rows)
n_rows_even = n_rows - n_rows%2
(pairs,) = np.nonzero(arr[0:n_rows_even:2, 1] == arr[1:n_rows_even:2, 1])
top = 2*pairs
middle = 2*pairs + 1
bottom = np.setdiff1d(all_rows, np.concatenate([top, middle]))
return arr[np.concatenate([top, middle, bottom])]
Demo
In [1056]: for x, y in zip(old_points, new_points):
...: x_new = rearrange(x)
...: print(np.array_equal(x_new, y))
True
True
I have a 3D matrix in python as the following:
import numpy as np
a = np.ones((2,2,3))
a[0,0,0] = 2
a[0,0,1] = 3
a[0,0,2] = 4
I want to convert this 3D matrix to a set of 2D matrices. I have tried np.reshape but it did not solve my problem. The final shape I am interested in is the following cascaded vesrsion:
[[ 2. 1. 3. 1. 4. 1.]
[ 1. 1. 1. 1. 1. 1.]]
However, np.reshape gives me the following
[[ 2. 3. 4. 1. 1. 1.]
[ 1. 1. 1. 1. 1. 1.]]
How can I solve this?
Use transpose alongwith reshape -
a.transpose([0,2,1]).reshape(a.shape[0],-1)
Or use swapaxes that does the same job as transpose alongwith reshape -
a.swapaxes(2,1).reshape(a.shape[0],-1)
Sample run -
In [66]: a
Out[66]:
array([[[ 2., 3., 4.],
[ 1., 1., 1.]],
[[ 1., 1., 1.],
[ 1., 1., 1.]]])
In [67]: a.transpose([0,2,1]).reshape(a.shape[0],-1)
Out[67]:
array([[ 2., 1., 3., 1., 4., 1.],
[ 1., 1., 1., 1., 1., 1.]])
In [68]: a.swapaxes(2,1).reshape(a.shape[0],-1)
Out[68]:
array([[ 2., 1., 3., 1., 4., 1.],
[ 1., 1., 1., 1., 1., 1.]])
In my Python application I have a 3D matrix (array) such this:
array([[[ 1., 2., 3.]], [[ 4., 5., 6.]], [[ 7., 8., 9.]]])
and I would like to add, in a particular "line", for example, in the middle, zero arrays. At the end I would like to end with the following matrix:
array([[[ 1., 2., 3.]],
[[ 4., 5., 6.]],
[[ 0., 0., 0.]],
[[ 0., 0., 0.]],
[[ 7., 8., 9.]]])
Anybody knows how to solve this issue? I tried to use "numpy.concatenate", but it allow me only to add more "lines".
Thanks in advance!
Possible duplicate of
Inserting a row at a specific location in a 2d array in numpy?
For example:
a = array([[[ 1., 2., 3.]], [[ 4., 5., 6.]], [[ 7., 8., 9.]]])
output = np.insert(a, 2, np.array([0,0,0]), 0)
output:
array([[[ 1., 2., 3.]],
[[ 4., 5., 6.]],
[[ 0., 0., 0.]],
[[ 7., 8., 9.]]])
Why this works on 3D array?
See doc here.
It says:
numpy.insert(arr, obj, values, axis=None)
...
Parameters :
values : array_like
Values to insert into arr.
If the type of values is different from that of arr,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
values is converted to the type of arr. values should be shaped so that
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
arr[...,obj,...] = values is legal.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...
So it's very wise function!!
Is this what you want?
result = np.r_[ a[:2], np.zeros(1,2,3), a[2][None] ]
I'd do it this way:
>>> a = np.array([[[ 1., 2., 3.]], [[ 4., 5., 6.]], [[ 7., 8., 9.]]])
>>> np.concatenate((a[:2], np.tile(np.zeros_like(a[0]), (2,1,1)), a[2:]))
array([[[ 1., 2., 3.]],
[[ 4., 5., 6.]],
[[ 0., 0., 0.]],
[[ 0., 0., 0.]],
[[ 7., 8., 9.]]])
The 2 in (2,1,1) given to tile() is how many zero "rows" to insert. The 2 in the slice indexes is of course where to insert.
If you're going to insert a large amount of zeros, it may be more efficient to just create a big array of zeros first and then copy in the parts you need from the original array.
Why does the following code not produce the expected assignment?
A = np.array([[ 9., 2., 7.], [ 3., 3., 1.], [ 4., 1., 6.]])
L = np.zeros([3,3])
i = range(1,3)
L[i][:,[0]] = A[i][:,[0]] / A[0,0]
L continues to contain all zeros. How do I produce what I expect to see (i.e. [[ 0., 0., 0.], [ .333, 0., 0.], [ .444, 0., 0.]])?
You should do direct indexing L[i,0]=A[i,0]/A[0,0], otherwise you are working on a view rather than then a slice of the original array.