Instantiate A Class In A Groupby Method
I have the following class for a file: class File: def __init__(self, file_name, md5): self.file_name = file_name self.md5 = md5 def do_something(self):
Solution 1:
I'm not sure, if this is a solution. You can instantiate objects in the apply method. I created an example class and dataframe.
classTest:def__init__(self, a, b):
self.a = a
self.b = b
df = pd.DataFrame({
'group': list('abbaabcc'),
'group2': list('abababab'),
'a': [1,2,1,2,3,2,3,4],
'b': [3,4,2,3,4,5,3,4]
})
df
Output
group group2 ab0aa131bb242ba123ab234aa345bb256 c a337 c b44
Create Objects in apply
df.groupby(['group','group2'])[['a','b']].apply(
lambda x: [Test(e[0],e[1]) for _,e in x.iterrows()])
Output
group group2
a a [<__main__.Test object at 0x7f5351df0390>, <__...
b [<__main__.Test object at 0x7f5351df03d0>]
b a [<__main__.Test object at 0x7f5351df0450>]
b [<__main__.Test object at 0x7f5351df0490>, <__...
c a [<__main__.Test object at 0x7f5351df0550>]
b [<__main__.Test object at 0x7f5351df04d0>]
dtype:object
Post a Comment for "Instantiate A Class In A Groupby Method"