python - 如何将类中的函数应用到 Pandas Dataframe 中

标签 python pandas

我正在尝试使用计算值创建一个新列,该值是使用类中的方法计算的。
用于计算的类如下:

import functions_image_recognition as fir
class CompareImages():

    def __init__(self, url_1, url_2):
        self.img_url_1 = url_1
        self.img_url_2 = url_2

    def load_images(self, img_url, flag_color=False):
        req = urllib.request.urlopen(img_url)
        arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
        image = cv2.imdecode(arr, -1) # Load image as it is
        if not flag_color:
            return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Change color to greyscale
        else:
            return image # Original image

    def main_process_ssmi(self):
        imageA = self.load_images(self.img_url_1)
        imageB = self.load_images(self.img_url_2)
        (H, W) = imageA.shape
        imageB = cv2.resize(imageB, (W, H))
        (score, diff) = structural_similarity(imageA, imageB, full=True)
        result = float("{}".format(score))
        return result

数据框中列的名称是:seller_url,supplier_url
我想在数据框中创建一个新列,结果是在类中应用函数,并将结果附加到原始数据框中。
match_image = CompareImages(seller_url,supplier_url)
result = match_image.main_process_ssmi()

Dataset Sample

最佳答案

使用 Apply您可以按如下方式使用现有的类。

代码

df['new_column'] = df.apply(lambda row: CompareImages(row['seller_url'], row['supplier_url']).main_process_ssmi(), axis = 1)

说明

我们为每一行构造和对象并访问方法 main_process_ssmi。

在使用:
row['seller_url'] and row['supplier_url'] 

apply 函数传递行值,即每行的 Seller_url 和 supply_url 的值。

关于python - 如何将类中的函数应用到 Pandas Dataframe 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61192328/

相关文章:

python - 分组并附加列表和字符串

python - Python Lambda 函数的空参数

python - 如何在 DataFrame 中找到包含特定列表的行

python - Pandas 数据框 - 将行从一个数据框移动到另一个数据框

python - Pandas Dataframe 的复杂子集

python - 在 Pandas 数据框中查找最近的日期

Python 正则表达式首先找到 '&'

string - 用字典替换子字符串的最快方法(在大型数据集上)

python - 如果前一列中的值不同,则制作一个增加的计数器?

python - Webapp2重定向404错误