2

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)
3
  • why 12,50 ? shouln't it be (0,1) for the first 7? Row 0, Column 1? Commented Dec 17, 2021 at 14:42
  • Sorry. I have edited the question. Commented Dec 17, 2021 at 16:51
  • what will the output look like Commented Dec 17, 2021 at 18:32

2 Answers 2

2

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)]
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much it work just perfect. However, can this code be applied to dataframe?? instead of numpy array?
I mean can we change the code so that instead of number of column and row indexes, their label shows. For example: [(54.22, 30.92), (55.17, 31.22)], which the number is degree that are labels of rows and columns.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.