Find the matching string values โ€‹โ€‹and extract them separately, without specifying the match value (key)

I am trying to extract rows with matching Sample_IDs in the dataframe below:

df1 = pd.DataFrame([[1, 1.0, 2.3,0.2,0.53], [2, 3.35, 2.0,0.2,0.65], [2,3.4, 
               2.0,0.25,0.55], [3,3.4,2.0,0.25,0.55]],
               columns=["Sample_ID", "NaX", "NaU","OC","EC"])\
               .set_index('Sample_ID') 

      

In the above df1 dataframe, I would like to get only rows with Sample_ID of "2". Is there a way to do this without specifying the appropriate values, key?

As a result, I am looking for:

       NaX NaU OC  EC
Sample_ID                  
   2   3.35    2.0 0.20    0.65 
   2   3.40    2.0 0.25    0.55

      

Thanks for reading this!

+3


source to share


3 answers


Use .loc

:

df.loc[2]

      

Output:



            NaX  NaU    OC    EC
Sample_ID                       
2          3.35  2.0  0.20  0.65
2          3.40  2.0  0.25  0.55

      

To answer a question about a question, you can create a dictionary and save the following groups:

list_of_df = {}
for n,g in df1.groupby(level=0):
    list_of_df[n] = g

      

+5


source


Boolean indexing will do this. Sample_ID

is an index, so you need to use a condition df1.index

.

In [34]: df1[df1.index == 2]
Out[34]: 
            NaX  NaU    OC    EC
Sample_ID                       
2          3.35  2.0  0.20  0.65
2          3.40  2.0  0.25  0.55

      



As Scott Boston mentions, this df.loc

is another great alternative.

+5


source


g = df1.groupby(level=0)

      

Then grab whatever group you want with g.get_group(2)

            NaX  NaU    OC    EC
Sample_ID                       
2          3.35  2.0  0.20  0.65
2          3.40  2.0  0.25  0.55

      

But this is more important than necessary. Just select @ ScottBoston's answer.

+3


source







All Articles