Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas: Getting the Index of All Rows that Match a Column Value [duplicate]

I have the following Dataframe below:

Rec  Channel  Value1  Value2 
Pre             10      20
Pre             35      42
Event    A      23      39
FF              50      75
Post     A      79      11
Post     B      88      69

I am trying to determine the appropriate syntax for this Pandas Dataframe on how to index for all instances where the column 'Channel' is either equal to either A or B. Once all instances are found, I would like to print those out. Additionally, I would like to be able to call upon each index for further applications within the script.

I want the display to be:

Rec  Channel  Value1  Value2
Event   A       23      39
Post    A       79      11
Post    B       88      69

And then I want to have a 'for loop' that goes through and prints out each indexed instance separately so that it is easy to identify and call upon them individually for further uses in the script. Can someone please advise?

like image 298
bigballerbrand Avatar asked Aug 30 '25 15:08

bigballerbrand


1 Answers

You can use pd.Series.isin for this:

res = df[df['Channel'].isin({'A', 'B'})]

print(res)

#      Rec Channel  Value1  Value2
# 2  Event       A      23    39.0
# 4   Post       A      79    11.0
# 5   Post       B      88    69.0

To return the second row by index:

res2 = res.loc[2]

print(res2)

# Rec        Event
# Channel        A
# Value1        23
# Value2        39
# Name: 2, dtype: object
like image 81
jpp Avatar answered Sep 02 '25 15:09

jpp