Search code examples
pythonpandasstock

How to filter negative and positive returns by weekday in Python?


I need to either create a for loop or a list comprehension to filter out negative returns and positive returns by weekday.

I’m using a csv file of a stock ticker from yahoo finance. There is a column “weekday” and a column for “return”. What basic loop or list comprehension can I use?

I am using pandas but can do something without and not using numpy.


Solution

  • Suppose your df looks like this

      weekday   return
    0       M        1
    1       W       -3
    2       F        4
    3       T        5
    4       W       -3
    5       F       -2
    6       M       -4
    

    you can filter by weekday and negative return by

    df[(df['weekday'] == 'M') & (df['return'] < 0)]