1

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?

Zin Yosrim
  • 1,602
  • 1
  • 22
  • 40
  • 1
    Can you provide a minimal reproducible code for your class? – mozway Apr 06 '23 at 09:49
  • 3
    Just to mention that `f = lambda...` is against PEP8 – buran Apr 06 '23 at 09:50
  • 1
    Does this answer your question? [Python string to attribute](https://stackoverflow.com/questions/3253966/python-string-to-attribute) and [How to access (get or set) object attribute given string corresponding to name of that attribute](https://stackoverflow.com/q/2612610/4046632) – buran Apr 06 '23 at 09:53

1 Answers1

2

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')
mozway
  • 194,879
  • 13
  • 39
  • 75