I need to find a way to count how many times each number from 0 to 9 appears in a random matrix created using np.random.randint()
import numpy as np
p = int(input("Length of matrix: "))
m = np.random.randint(0,9,(p,p))
print(m)
For example if length of matrix = 4
[[3 4 6 5] [3 4 4 3] [4 2 4 8] [6 8 2 7]]
How many times does the number 4 appear? It should return 5.
You should be able to get this pretty simply:
list(m.flatten()).count(x)
Another option which is probably faster, is to use the numpy builtin count_nonzero():
np.count_nonzero(m == x)
Hooray builtin functions.
You can use sum function:
In [52]: m = np.random.randint(0,9,(4,4))
In [53]: m
Out[53]:
array([[8, 8, 2, 1],
[2, 7, 1, 2],
[8, 6, 8, 7],
[5, 2, 5, 2]])
In [56]: np.sum(m == 8)
Out[56]: 4
m == 8 will return a boolean array contains True for each 8 then since python evaluates the True as 1 you can sum up the array items in order to get the number of intended items.
If you want to get the frequency from all matrix elements, here's a simple solution using numpy.ndarray.flatten and collections.Counter:
import numpy as np
import collections
p = int(input("Length of matrix: "))
m = np.random.randint(0, 9, (p, p))
print(m)
print(collections.Counter(m.flatten()))
For example, when p=3 you'd get something like this:
[[8 4 8]
[5 1 1]
[1 1 1]]
Counter({1: 5, 8: 2, 4: 1, 5: 1})
You can flatten the matrix and then use the list count() method:
from collections import Counter
import numpy as np
p = int(input("Length of matrix: "))
m = np.random.randint(0,9,(p,p))
print(m)
flat = [item for sublist in m for item in sublist]
flat.count(4)
I would try numpy unique function with argument return_counts=True (see: https://numpy.org/doc/stable/reference/generated/numpy.unique.html).
import numpy as np
p = int(input("Length of matrix: "))
m = np.random.randint(0,9,(p,p))
# print(m)
un, nm = np.unique(m, return_counts = True)
# if number that you are looking for is 1 then:
print(nm[un==1])
Related
I have a numpy array, I want to replace whole values to zeros except some range of index.
1
2
3
4
5
I tried
Import numpy as np
data=np.loadtxt('data.txt')
print(data)
expected output
0
0
3
0
0
You can traverse the array with a for loop and check if the traversed element is in a list of desired selected values:
import numpy as np
a = np.array([1, 2, 3, 4, 5])
nums = [3]
for i in range(len(a)):
if a[i] in nums:
pass
else:
a[i] = 0
print(a)
Output:
[0 0 3 0 0]
As you're working with a numpy array, use vectorial methods.
Here isin to form a boolean mask for replacement:
data = np.array([1, 2, 3, 4, 5])
l = [3]
data[~np.isin(data, l)] = 0
data
# array([0, 0, 3, 0, 0])
I know that you cant stack or concatenate arrays of different lenghths in NumPy as all matrices need to be rectangular, but is there any other way to achieve this?
For example:
a = [1, 2 ,3]
b = [9, 8]
Stacking them would give:
c = [[1, 2, 3]
[9, 8]]
alternatively if there is no way to create the above how could I write a function to get this: (0 in place of missing element to fill matrix)?
c = [[1, 2, 3]
[9, 8, 0]]
This code worked for me:
a = [1, 2 ,3]
b = [9,8]
while len(b) != len(a):
if len(b) > len(a):
a.append(0)
else:
b.append(0)
final = np.array([a,b])
print(final)
The code is self explanatory, but I will try my best to give a valid explanation:
We take two lists (say a and b) and we compare there lengths, if they are unequal we add element (in this case 0) to the one whose length is lower, this loops until their lengths are equal, then it simply converts them into a 2D array in numpy
Also you can replace 0 with np.NaN if you want NaN values
I think what you are looking for is:
In:
from itertools import zip_longest
a = [1, 2 ,3]
b = [9, 8]
c = np.array(list(zip_longest(*[a,b])),dtype=float).transpose()
print(c)
Out:
[[ 1. 2. 3.]
[ 9. 8. nan]]
I haven't found a simple solution to move elements in a NumPy array.
Given an array, for example:
>>> A = np.arange(10).reshape(2,5)
>>> A
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
and given the indexes of the elements (columns in this case) to move, for example [2,4], I want to move them to a certain position and the consecutive places, for example to p = 1, shifting the other elements to the right. The result should be the following:
array([[0, 2, 4, 1, 3],
[5, 7, 9, 6, 8]])
You can create a mask m for the sorting order. First we set the columns < p to -1, then the to be inserted columns to 0, the remaining columns remain at 1. The default sorting kind 'quicksort' is not stable, so to be safe we specify kind='stable' when using argsort to sort the mask and create a new array from that mask:
import numpy as np
A = np.arange(10).reshape(2,5)
p = 1
c = [2,4]
m = np.full(A.shape[1], 1)
m[:p] = -1 # leave up to position p as is
m[c] = 0 # insert columns c
print(A[:,m.argsort(kind='stable')])
#[[0 2 4 1 3]
# [5 7 9 6 8]]
I have a 2d numpy array of floats, and I want to delete all rows in which the third column of that row contains a value less than x.
eg. [[3,4,5],[3,3,8],[4,2,1],[1,2,1]], with threshold 2, outputs [[3,4,5],[3,3,8]].
Try this one:
>>> import numpy as np
>>> x=np.array([[3,4,5],[3,3,8],[4,2,1],[1,2,1]])
>>> x=x[x[:,2]>=2]
>>> x
array([[3, 4, 5],
[3, 3, 8]])
Try this:
import numpy as np
array = np.array([[3,4,5],[3,3,8],[4,2,1],[1,2,1]])
array = np.array([x for x in array if x[2] > 2])
print (array)
You can use a list-comprehension:
import numpy as np
arr = np.array([[3,4,5],[3,3,8],[4,2,1],[1,2,1]])
threshold = 2
arr = np.array([row for row in arr if row[2] >= threshold])
print(arr)
Output:
[[3 4 5]
[3 3 8]]
Alternatively, you can use filter:
np.array([*filter(lambda r : r[2] >= threshold, arr)])
I have this m x n numpy array which I want to apply certain operation over the row elements. Although, it must be cast only on those elements whose index is prior to those specified by the entries on a vector of indexes.
I've already gone through the classic for-loop way, but I was expecting something more NumPythonic.
The following code would complete the job:
for i,j in enumerate(x):
M[i, 0:j] = 2*M[i, 0:j]
But I was look for a broadcast, no-for approach. Any Ideas?
For example, lets say that
M = [[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9,10]]
x = [2, 3]
and our application is to double certain element. According to the indexes specified in x we should have the resulting array:
M = [[ 2, 4, 3, 4, 5],
[12,14,16, 9,10]]
Here are two related ways which turn out to be roughly equally fast:
import numpy as np
from timeit import timeit
M = [[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9,10]]
x = [2, 3]
def f():
MM = np.array(M)
xx = np.array(x)
MM[np.arange(5)<xx[:,None]] *= 2
return MM
def g():
MM = np.array(M)
xx = np.array(x)
MM *= 1 + (np.arange(5)<xx[:,None])
return MM
print(f())
print(g())
M = 1000*M
x = 1000*x
print(timeit(f,number=1000))
print(timeit(g,number=1000))
Sample run:
[[ 2 4 3 4 5]
[12 14 16 9 10]]
[[ 2 4 3 4 5]
[12 14 16 9 10]]
1.1994759310036898
1.1547658089984907