4

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?

2 Answers2

5

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
jpp
  • 159,742
  • 34
  • 281
  • 339
  • That worked, thank you very much! The only thing that I am curious about is that I am going to need the return of the row by index to be in a 'for loop' so that for each time that an A or B was found in the Channel column, the loop will print out each each instance separately if that makes sense? Can you please advise? – bigballerbrand Apr 20 '18 at 13:26
  • @bigballerbrand, That's another question. You can try: [How to iterate over rows in a DataFrame in Pandas?](https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas) – jpp Apr 20 '18 at 13:38
2

Use query

res = df.query('Channel in ["A", "B"]')

res

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

If you want the index so you can utilize for another purpose:

Either

idx = res.index

Or, without making res

idx = df.index[df.Channel.isin(['A', 'B'])]
piRSquared
  • 285,575
  • 57
  • 475
  • 624
  • That worked, thank you very much! The only thing that I am curious about is that I am going to need the return of the row by index to be in a 'for loop' so that for each time that an A or B was found in the Channel column, the loop will print out each each instance separately if that makes sense? Can you please advise? – bigballerbrand Apr 20 '18 at 13:34
  • I've updated my post – piRSquared Apr 20 '18 at 13:39