Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am working on pandas using a huge dataset that consists of helper functions and the main function which used the helper functions as getting the result.

I have many functions that accept the columns as there input. Since the input is taken from the user. Problem is that I have too many functions that input pretty much the same column.

To avoid so many functions I am thinking to use the dictionary. Were I can pass all the parameters into the function without modifying the dictionary. The function should ignore the keywords which are present in the dictionary if they are not inputted by the user.

Let us consider an example :

 def func1(a, b, c):

        return a + b * c

This is the dictionary which I wanted to pass to my function;

 input_dict = {'a': 1,

                 'b': 2,

                 'c': 3,

                 'd': 4}

If I call the function using the dict

 value = func1(**input_dict)

I am getting error as unexpected argument d

1 Answer

0 votes
by (36.8k points)

You want to create the dictionary and pass the values into the function is a good idea. I have provided the code below;

from operator import attrgetter

class Foo:

    def __init__(self, a, b, c, d):

        self.a = a

        self.b = b

        self.c = c

        self.d = d

    def func1(self):

        a, b, c = attrgetter('a', 'b', 'c')(self)

        return a + b * c

f = Foo(1, 2, 3, 4)

value = f.func1()

So in the above code, I have used the instance of the class. Each instance has a helper function.we are using only those instance which is inputted.

You can use the attrgetter function for migrating the existing functions as methods. So you can define the function as shown below:

def func1(self):

    return self.a + self.b * self.c

Improve your knowledge in data science from scratch by click on the link Data Science

 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...