Hello I'm new in python I couldn't solve my problem. Suppose I have a list (a), this list has many matricies which is the same shape. I want to get one matrix that result of mean of each elements.
here is the list and its elements:
a[0]=[1 2 3]
a[1]=[3 4 5]
a[2]=[6 7 8]
Here is the desired matrix:
mean=[10/3 13/3 16/3]
Mean of each element of a list of matrices
Actually, this answer is good for me but it's for the R, not python. Sorry if I made a mistake while asking a question.
Using Python list comprehension
a = [[1, 2, 3],
[3, 4, 5],
[6, 7, 8]]
mean = [sum(row)/len(row) for row in zip(*a)] # use zip(*a) to transpose matrix
# since sum along columns
# by summing rows of transposed a
# [3.3333333333333335, 4.333333333333333, 5.333333333333333]
Here is a pure python solution that would work with any matrice dimension:
matrice = [
[1, 2, 3],
[3, 4, 5],
[6, 7, 8]
]
def mean_mat(mat):
dim_axis_0 = mat.__len__()
mean = [0 for i in range(dim_axis_0)]
for vector in mat:
for i, value in enumerate(vector):
mean[i] += (value / dim_axis_0)
return mean
print(mean_mat(matrice))
>>> [3.333333333333333, 4.333333333333334, 5.333333333333334]
However, as user1740577 pointed out, you should checkout the Numpy library.
try this:
import numpy as np
a= [[1,2,3],[3,4,5],[6,7,8]]
np.mean(a, axis=0)
# array([3.33333333, 4.33333333, 5.33333333])
Related
Given indexes for each row, how to return the corresponding elements in a 2-d matrix?
For instance, In array of np.array([[1,2,3,4],[4,5,6,7]]) I expect to see the output [[1,2],[4,5]] given indxs = np.array([[0,1],[0,1]]). Below is what I've tried:
a= np.array([[1,2,3,4],[4,5,6,7]])
indxs = np.array([[0,1],[0,1]]) #means return the elements located at 0 and 1 for each row
#I tried this, but it returns an array with shape (2, 2, 4)
a[idxs]
The reason you are getting two times your array is that when you do a[[0,1]] you are selecting the rows 0 and 1 from your array a, which are indeed your entire array.
In[]: a[[0,1]]
Out[]: array([[1, 2, 3, 4],
[4, 5, 6, 7]])
You can get the desired output using slides. That would be the easiest way.
a = np.array([[1,2,3,4],[4,5,6,7]])
a[:,0:2]
Out []: array([[1, 2],
[4, 5]])
In case you are still interested on indexing, you could also get your output doing:
In[]: [list(a[[0],[0,1]]),list(a[[1],[0,1]])]
Out[]: [[1, 2], [4, 5]]
The NumPy documentation gives you a really nice overview on how indexes work.
In [120]: indxs = np.array([[0,1],[0,1]])
In [121]: a= np.array([[1,2,3,4],[4,5,6,7]])
...: indxs = np.array([[0,1],[0,1]]) #
You need to provide an index for the first dimension, one that broadcasts with with indxs.
In [122]: a[np.arange(2)[:,None], indxs]
Out[122]:
array([[1, 2],
[4, 5]])
indxs is (2,n), so you need a (2,1) array to give a (2,n) result
I have several arrays of data, collected into a single array. I want to loop over it, and do operations on each of the inner arrays. What would be the correct way to do this in Numpy
import numpy as np
a = np.arange(9)
a = a.reshape(3,3)
for val in np.nditer(a):
print(val)
and this gives:
0
1
2
3
4
5
6
7
8
But what I want is (something like):
array([0 1 2])
array([3 4 5])
array([6 7 8])
I have been looking at this page: https://docs.scipy.org/doc/numpy-1.15.0/reference/arrays.nditer.html but so far have not found the answer. I also know I can do it with a plain for loop but I am assuming there is a more correct way. Any help would be appreciated, thank you.
You can use apply_along_axis but it depends on what your ultimate goal/output is. Here is a simple example showing this.
a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
np.apply_along_axis(lambda x: x + 1, 0, a)
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Actually when you use reshape it will return an array of lists not arrays.
If you would like to get each individual list you could just use
a = np.arange(9)
a = a.reshape(3,3)
for val in a:
print(val)
Why not just simply loop over the array where you get individual rows in the for loop
import numpy as np
a = np.arange(9)
a = a.reshape(3,3)
for val in a:
print(val)
# [0 1 2]
# [3 4 5]
# [6 7 8]
I am trying to find an efficient way to multiply specific values within a matrix for a given scalar. Let's see a quick example.
Given a matrix M of values between 1 and 10 like so:
I want to multiply every cell that has value smaller than 3, by 2. Now I know I can find the coordinates of all items that have value 1 in tensorflow with tf.where(M < 3) but I am struggling to find a good scalable solution to attain what I want. The transformation should be something like this:
How can I leverage this info to multiply only the cells at the given coordinates by 2 ?
Keep in mind that my matrices might be mich bigger than 3x3
M = np.array([[1, 5, 8],[2, 2, 2], [9, 7, 6]])
M[M==1] = 2
print(M)
array([[2, 5, 8],
[2, 2, 2],
[9, 7, 6]])
I found out how to do this in tensorflow without having to do any transformation from numpy to tensorflow and vice-versa.
my_matrix = tf.constant([[1, 5, 8], [2, 2, 2], [9, 7, 6]])
result = tf.where(
tf.less(my_matrix, tf.constant(3)),
tf.scalar_mul(2, my_matrix),
my_matrix
)
#Josh answer helped me look into the right direction
This question already has answers here:
Efficient Numpy 2D array construction from 1D array
(7 answers)
Closed 6 years ago.
I have an array like
[1,3,4,5,6,2,1,,,,]
now, I want to change it to
[[1,3,4],[3,4,5],[4,5,6],[5,6,2],,,,]
How can I achieve this using numpy? Is there any function to do so? And, using loop is not an option.
np.lib.stride_tricks.as_strided method will does that.
Here strides is (4,4) for 32 bit int. If you want more flexible code, I have commented stride parameter in the code. shape parameter determines output array dimensions.
> import numpy as np
> A = [1,2,3,4,5,6]
> n = 3 # output matrix has 3 columns
> m = len(A) - (n-1) # calculate number of output matrix rows using input matrix length
> # strides_param = np.array(A, dtype=np.int32).strides * 2
> np.lib.stride_tricks.as_strided(A, shape=(m,n), strides=(4,4))
array([[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6]])
Using list comprehension instead of a library but why make it complicated. (Do you consider this a loop?)
x = [1,3,4,5,6,2,1]
y = [x[n:n+3] for n in range(len(x)-2)]
Result is:
[[1, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 2], [6, 2, 1]]
Suppose inputs are like below.
indexSet1 = [0,1,2]
indexSet2 = [1,2]
A = [[1,2,3],[4,5,6],[7,8,9]]
Then I want to get a matrix whose height is 3 and width is 2 respectively and elements corresponds to indexSet1's value and indexSet2's one.
In short, I want to a array [[2,3],[4,5],[7,8]] from A by indexSet1 and indexSet2.
When I code like below, I can not get my desire result.
>>> import numpy as np
>>> np.array(A)[np.array(indexSet1),np.array(indexSet2)]
array([5, 9])
Can anyone know wise methods?
Sorry for my poor English.
And thank you in advance.
Using nested list comprehension:
>>> indexSet1 = [0,1,2]
>>> indexSet2 = [1,2]
>>> A = [[1,2,3],[4,5,6],[7,8,9]]
>>> [[A[i][j] for j in indexSet2] for i in indexSet1]
[[2, 3], [5, 6], [8, 9]]
In NumPy you can do something like this:
>>> A = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> A[np.array(indexSet1)[:, None], indexSet2]
array([[2, 3],
[5, 6],
[8, 9]])