Reputation: 389
I need to build classes and methods for different calculation steps:
I got a dataframe with numerical columns A,B,C.
I want the class to initialize the columns of the dataframe as inputs so I can call following methods:
Method1: sum(A)
Method2: sum(A)*B
How do you do that in Python?
I know it is a really general question, but I only came across really abstract OOP tutorials. I need it more specific on calculations & finance. A good source to some tutorial would also help.
Thanks,
KS
Upvotes: 0
Views: 756
Reputation: 5034
You can do like this.
import pandas as pd
import numpy as np
class MyCalculator:
def __init__(self, df):
self.df = df
def m1(self):
return self.df['A'].sum()
def m2(self):
# return np.multiply(self.m1(), self.df['B']).values
return np.multiply(self.m1(), self.df['B']).values.reshape(-1, 1)
d = {
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]
}
def main():
df = pd.DataFrame(d)
print(f'frame:\n {df}')
b = MyCalculator(df)
print(f'method 1:\n {b.m1()}')
print(f'method 2:\n {b.m2()}')
# start
main()
Output:
frame:
A B C
0 1 4 7
1 2 5 8
2 3 6 9
method 1:
6
method 2:
[[24]
[30]
[36]]
Upvotes: 1