Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does "by = lambda x: lambda y: getattr(y, x)" mean?

There is a dataFrame named "subset" and the codes are as follows. pd is the nickname of pandas. I can't figure out the meaning of by = lambda x: lambda y: getattr(y, x).

pivot = pd.pivot_table(subset, values='count', rows=['date'], cols=['sample'], fill_value=0)
by = lambda x: lambda y: getattr(y, x)
grouped = pivot.groupby([by('year'),by('month')]).sum()
like image 682
zhql0907 Avatar asked Jun 28 '26 03:06

zhql0907


1 Answers

by = lambda x: lambda y: getattr(y, x) is equivalent to the following:

def by(x):
    def getter(y):
        return getattr(y, x)
    return getter

getattr(a, b) gets an attribute with the name b from an object named a.

So by('bar') returns a function that returns the attribute 'bar' from an object.

by('bar')(foo) means getattr(foo, 'bar') which is roughly foo.bar.

If that doesn't help, let us know which part you're still having trouble with.

like image 70
user94559 Avatar answered Jun 29 '26 16:06

user94559