Extract a specific value in dataframe column name and row index

Viewed 138

I have a dataframe with the shape of (5, 7). The column and row index are named from 0~6and 0~4 respectively. This dataframe (Matrix) consists of only four values such as 5,7,8 and 9.

However there are 6 seven values 6 eight values 7 nine values and 16 five values.

Can anyone suggest a code that can extract the number sevens (7), values of column and row??

For example, 1st seven (2, 1)-->(column name, row index) 2nd seven (2, 2)

and do this for eights and nines and etc.

import numpy as np
import pandas as pd

arr = np.array([[5,7,7,8,8,9,5],
               [5,5,8,9,8,5,7],
               [5,5,7,9,9,5,5],
               [5,5,5,9,8,7,5],
               [5,9,9,8,7,5,5]])

df = pd.DataFrame(arr)
2 Answers

Use np.where

np.where(arr==7)
Out[64]: 
(array([0, 0, 1, 2, 3, 4], dtype=int64),
 array([1, 2, 6, 2, 5, 4], dtype=int64))

Change to your format with zip

a = np.where(arr==7)
list(zip(a[0],a[1]))
Out[69]: [(0, 1), (0, 2), (1, 6), (2, 2), (3, 5), (4, 4)]

use two loops

arr = np.array([[5,7,7,8,8,9,5],
               [5,5,8,9,8,5,7],
               [5,5,7,9,9,5,5],
               [5,5,5,9,8,7,5],
               [5,9,9,8,7,5,5]])

def find_7(arr):
    for i in range(len(arr)):
        for j in range(len(arr[i])):
            if arr[i][j] == 7:
                print("row={row}, col={col}".format(row=i,col=j))

print(find_7(arr))

output

row=0, col=1
row=0, col=2
row=1, col=6
row=2, col=2
row=3, col=5
row=4, col=4
Related