Pass class method name as a parameter
Question:
I want to change the last line of following code
import io
import pandas as pd
writer = io.BytesIO()
data = [{"createdAt": 2021, "price": 10}, {"createdAt": 2022, "price": 20} ]
pd.DataFrame(data).to_csv(self.writer, header="true", index=False)
so that I can pass the name of the class method to_csv
as an argument.
Like
f = lambda x: pd.DataFrame(data).x(self.writer, header="true", index=False)
f('to_csv') # should do exactly the same as pd.DataFrame(data).x(.....
I tried to_csv
, to_csv()
as an argument as well. May I ask for help for fixing this?
Answers:
Do you want getattr
?
f = lambda x: getattr(pd.DataFrame(data), x)(self.writer, header=True, index=False)
f('to_csv')
Or with a function:
def f(x):
return getattr(pd.DataFrame(data), x)(self.writer, header=True, index=False)
f('to_csv')
I want to change the last line of following code
import io
import pandas as pd
writer = io.BytesIO()
data = [{"createdAt": 2021, "price": 10}, {"createdAt": 2022, "price": 20} ]
pd.DataFrame(data).to_csv(self.writer, header="true", index=False)
so that I can pass the name of the class method to_csv
as an argument.
Like
f = lambda x: pd.DataFrame(data).x(self.writer, header="true", index=False)
f('to_csv') # should do exactly the same as pd.DataFrame(data).x(.....
I tried to_csv
, to_csv()
as an argument as well. May I ask for help for fixing this?
Do you want getattr
?
f = lambda x: getattr(pd.DataFrame(data), x)(self.writer, header=True, index=False)
f('to_csv')
Or with a function:
def f(x):
return getattr(pd.DataFrame(data), x)(self.writer, header=True, index=False)
f('to_csv')