[英]Instantiate a class in a groupby method
我有以下 class 文件:
class File:
def __init__(self, file_name, md5):
self.file_name = file_name
self.md5 = md5
def do_something(self):
...
是否可以直接從 pandas 中的groupedby
映射創建此 object。 例如這樣的:
df_grouped = df.groupby(by=['resolution','media_type', 'asset_type'])
df_grouped_2 = df_grouped.apply(lambda x: File(x['file_name'], x['md5']))
print (df_grouped_2)
我應該能夠得到類似的東西:
# resolution media_type asset_type
# HD Video Feature [<obj1>, <obj2>, ...]
# Promo [<obj1>]
# Trailer [<obj1>, <obj2>, ...]
我怎么能做類似上面的事情(我需要在class
上添加任何其他方法,例如__hash__
?)
我不確定,如果這是一個解決方案。 您可以在 apply 方法中實例化對象。 我創建了一個示例 class 和 dataframe。
class Test:
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 a b
0 a a 1 3
1 b b 2 4
2 b a 1 2
3 a b 2 3
4 a a 3 4
5 b b 2 5
6 c a 3 3
7 c b 4 4
在應用中創建對象
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.