zelenov aleksey - 8 months ago 49

Python Question

i have a matrix in pandas

`print reducedMatrix`

0 1 3 4

1 2 99991 0 0

2 0 4 0 1

3 3 0 9991 2

4 1 0 2 99989

and want to iterate over it and print i and j for zero values, I use:

`for i,rows in reducedMatrix.iterrows():`

for j,cols in reducedMatrix.iteritems():

if (reducedMatrix[i][j] == 0): #here we check all zero values

print i,j

but it does not work

the expected output

`1,3`

1,4

2,0

2,3

3,0

4,1

It's essential to save row and col names

how do I achieve that?

Thanks in advance for any help!

Answer

I would recommend using numpy's `where`

function.

```
np.where(df.values == 0)
```

will return the indices of rows and columns that match the condition. In order to retrieve the original row and column names:

```
rows, cols = np.where(df.values == 0)
list(zip(df.index[rows], df.columns[cols]))
```

Source (Stackoverflow)