Home > Back-end >  How to extract the index of an element that can be found on several rows
How to extract the index of an element that can be found on several rows

Time:01-06

I am looking to extract column name and index of elements from a dataframe

import numpy as np
import pandas as pd
import random
lst = list(range(30))
segments = np.repeat(lst, 3)
random.shuffle(segments)
segments = segments.reshape(10, 9)
col_names = ['lz' str(i) for i in range(95,104)]
rows_names = ['con' str(i) for i in range(0,10)]
df = pd.DataFrame(segments, index=rows_names, columns=col_names)

      lz95  lz96  lz97  lz98  lz99  lz100  lz101  lz102  lz103
con0     6     9    11     7     9     24     18     10      1
con1    24     5    21    15    18     25     24      7     29
con2    17    27     2     0    11     11     18     23      0
con3    16    22    20    22    20     14     14      0      8
con4    10    10     3    13    25     14      9     17     16
con5     3    28    22     2    27     12     16     21      4
con6    26     1    19     7    19      6     29     15     26
con7    26    28     4    13    23     23      1     25     19
con8    28     8     3     6     5      8      4      5     29
con9     2    15    21    27    17     13     12     12     20

For value=12, I am able to extract the column name lz_val = df.columns[df.isin([12]).any()] But not for rows as it extract all indexes

con_val = df[df==12].index
Index(['con0', 'con1', 'con2', 'con3', 'con4', 'con5', 'con6', 'con7', 'con8',
       'con9'],
      dtype='object')

CodePudding user response:

What about using np.where?

rows, cols = np.where(df == 12)

rows = df.index[rows]
cols = df.columns[cols]
>>> rows
Index(['con5', 'con9', 'con9'], dtype='object')
>>> cols
Index(['lz100', 'lz101', 'lz102'], dtype='object')
  • Related