![]() |
How to apply a class method to an entire dataframe column - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to apply a class method to an entire dataframe column (/thread-31780.html) |
How to apply a class method to an entire dataframe column - tirtha9 - Jan-03-2021 How can i apply a class method to an entire dataframe? A minimal code is here for the problem: I have a Price time series dataframe df with these columns column 1 date is a data object, other columns are float: Date | Open | High | Low | Close I have a method of a class as below: class MyScanner(): def __init__(self, df, scandate): self.df = df self.mydate = scandate #get the index to current date self.currentindex = df[df['Date'] == scandate].index[0] #Next Date High Low self.d1 = self.df[self.df.index == self.currentindex+1] self.h1 = self.d1['High'].max() self.l1 = self.d1['Low'].min() #Similarly assigned h2,l2,h3,l3 # stock price have made lower high and lower lows for next 3 days def isbearish(): if (self.h1 > self.h2 > self.h3) &\ (self.l1 > self.l2 > self.l3): return True # stock have made lower high and lower lows for next 3 days def isbullish(): if (self.h1 < self.h2 < self.h3) &\ (self.l1 < self.l2 < self.l3): return True # similar other functions which uses next 3 days high lows logic def issomething(): ..check something.. return True So now I can run this for a particular date: MyScanner(df, Date).isbullish() This will return True if the next 3 'Date' matches the called method condition. Now my query is I want to create a new Column called 'ISBullish', and apply this above method for respective dates in the Date Column to the whole data frame. This new Column will have either True or None, based on next 3 days data. I am stuck with the syntax to be passed to the apply method: df['ISBullish'] = df.Date.apply(MyClass(df, somedate).isbullish()) RE: How to apply a class method to an entire dataframe column - klllmmm - Jan-03-2021 Hi @tirtha9, Good day! Hope the below answer helps df2['ISBearish'] = df2['Date'].apply(lambda x: (Scanner(df2, x).isbearish2())) print(df2)
|