Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select dataframe row from rowname using case-insensitive (like `grep -i`)

I have a data frame that looks like this:

In [1]: mydict = {"1421293_at Hdgfl1":[2.140412,1.143337,3.260313],
                  "1429877_at Lrriq3":[9.019368,0.874524,2.051820]}

In [3]: import pandas as pd

In [4]:  df = pd.DataFrame.from_dict(mydict, orient='index')

In [5]: df
Out[5]:
                          0         1         2
1421293_at Hdgfl1  2.140412  1.143337  3.260313
1429877_at Lrriq3  9.019368  0.874524  2.051820

What I want to do is to select the the row from the row name, using a case-insensitive query. For example given the query "hdgfl1" it should return:

                                         0                1               2
1421293_at Hdgfl1                 2.140412          1.143337          3.260313

"hdgfl1" is the case-insensitive query of "1421293_at Hdgfl1". Basically equivalent to grep -i.

What's the way to do it?

like image 685
pdubois Avatar asked Feb 12 '23 04:02

pdubois


1 Answers

You can do it like this:

query = 'hdgfl1'
mask = df.index.to_series().str.contains(query, case=False)
df[mask]

Another possibility would be:

mask = df.reset_index()['index'].str.contains(query, case=False)

but this is 2x slower.

like image 113
elyase Avatar answered Feb 16 '23 04:02

elyase