python - 对数据帧的每一行应用函数并同时递增计数器

标签 python pandas dataframe apply

我知道我可以使用 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中,functions are first class citizens ,即使是属于对象的,实现您想要的目的的一种方法如下:

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)

输出

0    2
1    4
2    6
Name: Number, dtype: int64

请注意,一等公民身份意味着您不需要创建 lambda,您可以传递函数本身。

关于python - 对数据帧的每一行应用函数并同时递增计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64706103/

相关文章:

python - 如何将图像的每一帧的二维数组写入csv?

python - 将自己的测试方法名称注入(inject) pytest 输出

python - 索引错误: list index out of range (In whoosh Search Engine library) error at

python - 将 Pandas Dataframe 日期索引和列转换为 Numpy 数组

python - 错误 :root:code for hash md5 was not found

python - 如何计算python中某个范围内不为零的行数?

python - 使用 map 创建新列时处理 PerformanceWarning

python - 如何通过在特定条件下添加列来丰富数据框

python - 使用日期时间索引或列查询 Python Pandas DataFrame

python - 迭代读取 Pandas DataFrame 的 (tsv) 文件