应用于PANDAS数据框的递归功能的全局计数器
在来自在数据框的每一行上应用功能,并同时增加计数器将递归功能应用于终止计数器以更新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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论