Dustin
Dustin

Reputation: 73

Wrap a pandas function around my own created function

I'm having a Tweetanalyzer class, having a dataframe as an instancevariable.

Now I want to create a write_to_csv function which can take all parameters of the pandas to_csv function.

The reason Im doing it is I dont want to call -> Tweetanalyzer.df.to_csv just Tweetanalyzerobject.write_to_csv but with the same functionality as to_csv.

I guess wrapping the function could be the right way including *args and **kwargs but I'm not getting it to work.

class TweetAnalyzer:

    def __init__(self, tweets, df = pd.DataFrame({'A' : []})):

        self.tweets = tweets
        if df.empty:
            self.df = self.tweets_to_dataframe(self.tweets)
        else:
            self.df = df

    def write_to_csv(self):

        self.df.to_csv()

So if i call object.write_to_csv(encoding = "utf-8"), it will be parsed into the to_csv code and the code will work without specifying "encoding" in my function write_to_csv.

Thank you!!!

Upvotes: 2

Views: 501

Answers (1)

Dustin Michels
Dustin Michels

Reputation: 3226

Yup, using *args and **kwargs is probably the right idea! Something like this:

class TweetAnalyzer:
    def __init__(self, tweets, df=pd.DataFrame({"A": []})):
        self.tweets = tweets
        if df.empty:
            self.df = self.tweets_to_dataframe(self.tweets)
        else:
            self.df = df

    def write_to_csv(self, *args, **kwargs):
        self.df.to_csv(*args, **kwargs)

For a fuller explanation, see: What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

Upvotes: 2

Related Questions