应用于PANDAS数据框的递归功能的全局计数器

发布于 2025-01-31 15:39:55 字数 1565 浏览 2 评论 0原文

在来自在数据框的每一行上应用功能,并同时增加计数器将递归功能应用于终止计数器以更新pandas dataframe中的字典并返回更新的字典:

import pandas as pd

data = pd.DataFrame({'dict': [{}, {}, {}]})

class DictModifier:

    def __init__(self, seed):
        self.counter = seed
        
    def update_dict(self, d: dict) -> dict:
#         global counter
        print(f"COUNTER:{self.counter}")
        
        keys=['a','b']
        values=[1, 2]
        for k,v in zip(keys,values):
            d.update({k:v})
        print(d)
        self.counter+=1
        if self.counter==3:
            return d
        return update_dict(d)

fun = DictModifier(0)

data['mod_dict'] = data["dict"].apply(fun.update_dict)
print(data)

不幸的是,这给出了错误:

COUNTER:0
{'a': 1, 'b': 2}
COUNTER:<__main__.Counter object at 0x7f2c78dd45e0>
{'a': 1, 'b': 2}

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [1062], in <module>
...

Input In [1062], in DictModifier.update_dict(self, d)
     21 if self.counter==3:
     22     return d
---> 23 return update_dict(d)

Input In [1037], in update_dict(d)
      7     d.update({k:v})
      8 print(d)
----> 9 counter+=1
     10 if counter==3:
     11     return d

TypeError: unsupported operand type(s) for +=: 'Counter' and 'int'

预期结果:

results = pd.DataFrame({'dict': [{}, {}, {}],'mod_dict': [{'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}]})

Following inspiration from Apply function on each row of a dataframe and increment a counter at the same time to apply recursive function with a termination counter to update a dictionary in a pandas dataframe and return the updated dictionary:

import pandas as pd

data = pd.DataFrame({'dict': [{}, {}, {}]})

class DictModifier:

    def __init__(self, seed):
        self.counter = seed
        
    def update_dict(self, d: dict) -> dict:
#         global counter
        print(f"COUNTER:{self.counter}")
        
        keys=['a','b']
        values=[1, 2]
        for k,v in zip(keys,values):
            d.update({k:v})
        print(d)
        self.counter+=1
        if self.counter==3:
            return d
        return update_dict(d)

fun = DictModifier(0)

data['mod_dict'] = data["dict"].apply(fun.update_dict)
print(data)

Unfortunately this gives the error:

COUNTER:0
{'a': 1, 'b': 2}
COUNTER:<__main__.Counter object at 0x7f2c78dd45e0>
{'a': 1, 'b': 2}

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [1062], in <module>
...

Input In [1062], in DictModifier.update_dict(self, d)
     21 if self.counter==3:
     22     return d
---> 23 return update_dict(d)

Input In [1037], in update_dict(d)
      7     d.update({k:v})
      8 print(d)
----> 9 counter+=1
     10 if counter==3:
     11     return d

TypeError: unsupported operand type(s) for +=: 'Counter' and 'int'

Expected results:

results = pd.DataFrame({'dict': [{}, {}, {}],'mod_dict': [{'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}]})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文