How to find list rows and columns index in Python - python

I am trying to print row and column index in list.
I've used (loop below) this but Its one or the other..
a = [[0,0,1],
[0,1,0],
[1,0,0]]
def a():
x = 0
for sol in solutions:
print(sol)
for row in sol:
print(row)
I am trying to print
(0,2) (1,1) (2,0)
Index of 1s
Thank You

You can use enumerate to generate indices for a list:
for row, sublist in enumerate(a):
for column, item in enumerate(sublist):
if item:
print((row, column))
This outputs:
(0, 2)
(1, 1)
(2, 0)

If you like numpy you can turn it into a numpy array and use argwhere()
import numpy as np
a = [[0,0,1],
[0,1,0],
[1,0,0]]
a = np.array(a)
answer = np.argwhere(a==1)
This will output:
[[0 2]
[1 1]
[2 0]]

Related

Remove duplicate index in 2D array

I have this 2D numpy array here:
arr = np.array([[1,2],
[2,2],
[3,2],
[4,2],
[5,3]])
I would like to delete all duplicates corresponding to the previous index at index 1 and get an output like so:
np.array([[1,2],
[5,3]])
However, when I try my code it errors.
Here is my code:
for x in range(0, len(arr)):
if arr[x][1] == arr[x-1][1]:
arr = np.delete(arr, x, 0)
>>> IndexError: index 3 is out of bounds for axis 0 with size 2
Rather than trying to delete from the array, you can use np.unique to find the indices of first occurrences of the unique values in the second columns and use that to pull those values out:
import numpy as np
arr = np.array([[1,2],
[2,2],
[3,2],
[4,2],
[5,3]])
u, i = np.unique(arr[:,1], return_index=True)
arr[i]
# array([[1, 2],
# [5, 3]])

Numpy - Index last dimension of array with index array

I'm trying to index the last dimension of a 3D matrix with a matrix consisting of indices that I wish to keep.
I have a matrix of thrust values with shape:
(3, 3, 5)
I would like to filter the last index according to some criteria so that it is reduced from size 5 to size 1. I have already found the indices in the last dimension that fit my criteria:
[[0 0 1]
[0 0 1]
[1 4 4]]
What I want to achieve: for the first row and first column I want the 0th index of the last dimension. For the first row and third column I want the 1st index of the last dimension. In terms of indices to keep the final matrix will become a (3, 3) 2D matrix like this:
[[0,0,0], [0,1,0], [0,2,1];
[1,0,0], [1,1,0], [1,2,1];
[2,0,1], [2,1,4], [2,2,4]]
I'm pretty confident numpy can achieve this, but I'm unable to figure out exactly how. I'd rather not build a construction with nested for loops.
I have already tried:
minValidPower = totalPower[:, :, tuple(indexMatrix)]
But this results in a (3, 3, 3, 3) matrix, so I am not entirely sure how I'm supposed to approach this.
With a as input array and idx as the indexing one -
np.take_along_axis(a,idx[...,None],axis=-1)[...,0]
Alternatively, with open-grids -
I,J = np.ogrid[:idx.shape[0],:idx.shape[1]]
out = a[I,J,idx]
You can build corresponding index arrays for the first two dimensions. Those would basically be:
[0 1 2]
[0 1 2]
[0 1 2]
[0 0 0]
[1 1 1]
[2 2 2]
You can construct these using the meshgrid function. I stored them as m1, and m2 in the example:
vals = np.arange(3*3*5).reshape(3, 3, 5) # test sample
m1, m2 = np.meshgrid(range(3), range(3), indexing='ij')
m3 = np.array([[0, 0, 1], 0, 0, 1], [1, 4, 4]])
sel_vals = vals[m1, m2, m3]
The shape of the result matches the shape of the indexing arrays m1, m2 and m3.

Index of an element in a numpy array

Given a matrix like the following:
A = np.array([[1,2,3],
[3,4,5],
[4,5,6]])
How can I pinpoint the index of an element of interest. For example, assume I would like to find the index of 2 in the first row of the np.array, like so:
A[0,:].index(2), but clearly this does not work because A[0,:] is not a list.
You can compare the array to the value 2, and then use where.
For example, to find the location of 2 in the first row of A:
In [179]: np.where(A[0, :] == 2)[0]
Out[179]: array([1])
In [180]: j = np.where(A[0, :] == 2)[0]
In [181]: A[0, j]
Out[181]: array([2])
where also works with higher-dimensional arrays. For example, to find 2 in the full array A:
In [182]: i, j = np.where(A == 2)
In [183]: A[i,j]
Out[183]: array([2])

Cummulative matrix multiplication on successive square arrays in an (M,M,N) or similar array?

Say I have N MxM arrays in a single MxMxN array. Is there any simple way in numpy to do a cummulative matrix multiplication of successive MxM arrays (the MxMxN array can be overwritten). I can do it with a loop as shown below but I'm wondering if there is a better way? Note the ordering MxMxN is not special, I could just as easily have NxMxM or something.
import numpy as np
a = np.arange(4).reshape((2,2))
n=3
b = np.dstack((a,)*n)
print(b[:,:,0])
#[b[:,:,k].dot(b[:,:, k - 1], out=b[:,:, k]) for k in range(1, n)]
for k in range(1, n):
b[:,:,k] = np.dot(b[:,:,k], b[:,:,k-1])
print(b[:, :, k])
From which I get the output:
[[0 1]
[2 3]]
[[ 2 3]
[ 6 11]]
[[ 6 11]
[22 39]]
I also tried the following list comprehension which failed:
[b[:,:,k].dot(b[:,:, k - 1], out=b[:,:, k]) for k in range(1, n)]
EDIT:
I'm intersted in all the intermediate results so b[:,:,0], b[:,:,0] x b[0:,:,1], b[:,:,0] x b[0:,:,1] x b[:,:,2], etc. not just the final b[:,:,0] x b[0:,:,1] x ... x b[:,:,N-1]
For a M*M*N array, how about:
reduce(np.dot, np.rollaxis(b, 2))
For Python 3 you need to import reduce from functools.

Initialize empty matrix in Python

I am trying to convert a MATLAB code in Python. I don't know how to initialize empty matrix in Python.
MATLAB Code:
demod4(1) = [];
I tried in Python
demod4[0] = array([])
but it gives error:
only length-1 arrays can be converted to Python scalars
If you are using numpy arrays, you initialize to 0, by specifying the expected matrix size:
import numpy as np
d = np.zeros((2,3))
>>> d
[[ 0. 0. 0.]
[ 0. 0. 0.]]
This would be the equivalent of MATLAB 's:
d = zeros(2,3);
You can also initialize an empty array, again using the expected dimensions/size
d = np.empty((2,3))
If you are not using numpy, the closest somewhat equivalent to MATLAB's d = [] (i.e., a zero-size matrix) would be using an empty list and then
append values (for filling a vector)
d = []
d.append(0)
d.append(1)
>>> d
[0, 1]
or append lists (for filling a matrix row or column):
d = []
d.append(range(0,2))
d.append(range(2,4))
>>> d
[[0, 1], [2, 3]]
See also:
initialize a numpy array (SO)
NumPy array initialization (fill with identical values) (SO)
How do I create an empty array and then append to it in NumPy? (SO)
NumPy for MATLAB users
You could use a nested list comprehension:
# size of matrix n x m
matrix = [ [ 0 for i in range(n) ] for j in range(m) ]
What about initializing a list, populating it, then converting to an array.
demod4 = []
Or, you could just populate at initialization using a list comprehension
demod4 = [[func(i, j) for j in range(M)] for i in range(N)]
Or, you could initialize an array of all zeros if you know the size of the array ahead of time.
demod4 = [[0 for j in range(M)] for i in range(N)]
or
demod4 = [[0 for i in range(M)]*N]
Or try using numpy.
import numpy as np
N, M = 100, 5000
np.zeros((N, M))
To init matrix with M rows and N columns you can use following pattern:
M = 3
N = 2
matrix = [[0] * N for _ in range(M)]
If you want to initialize the matrix with 0s then use the below code
# for m*n matrix
matrix = [[0] * m for i in range(n)]
M=[]
n=int(input())
m=int(input())
for j in range(n):
l=[]
for k in range(m):
l.append(0)
M.append(l)
print(M)
This is the traditional way of doing it matrix[m,n], However, python offers many cool ways of doing so as mentioned in other answers.
i find that this method is the easies method to create a matrix
rows = 3
columns = 4
matrix = [[0] * columns] * rows
my output:
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
if you want to print the matrix use this:
for i in range(rows):
for j in range(columns):
print(matrix[i][j], end=' ')
print()
my output:
0 0 0 0
0 0 0 0
0 0 0 0
rows = 3
columns = 2
M = [[0]*columns]*rows
Or you could also use '' instead of 0
print(M)
Output:
M = [[0, 0], [0, 0], [0, 0]]

Categories