我知道我可以使用apply()
在数据帧的每一行上应用函数,如下所示:
import pandas as pd
df = pd.DataFrame({'Name' : ['A', 'B', 'C'], 'Number' : [1,2,3]})
def func(row):
pass
df.apply(lambda x: func(x), axis =1 )
但我需要传递一个增量计数器func()
。类似下面的东西,但我不知道如何增加计数器!
import pandas as pd
df = pd.DataFrame({'Name' : ['A', 'B', 'C'], 'Number' : [1,2,3]})
def func(row, counter):
pass
counter = 0 #initial value
df.apply(lambda x: func(x, counter), axis =1 )
在Python中,职能是一等公民 https://realpython.com/lessons/functions-are-first-class-citizens-python/,即使是属于对象的,实现您想要的效果的一种方法如下:
import pandas as pd
df = pd.DataFrame({'Name': ['A', 'B', 'C'], 'Number': [1, 2, 3]})
class Counter:
def __init__(self, seed):
self.counter = seed
def fun(self, n):
if True: # if you need to check a condition
self.counter += 1 # add any value you see fit
return n + self.counter
counter = Counter(0)
result = df["Number"].apply(counter.fun)
print(result)
Output
0 2
1 4
2 6
Name: Number, dtype: int64
请注意,一等公民身份意味着您不需要创建 lambda,您可以传递函数本身。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)