python - 将函数应用于两个 DataFrame 列并从结果创建新列

标签 python python-3.x pandas difflib

我正在使用 python 3.5 和以下列开发 pandas.DataFrame:

dataframe.head(2)

    TwitterID      Fullname    Gender    City     Screen_Name   
0     12345       John Smith     M      London     J_smith47  
1     25486       Emily Reid     F      Brighton   emreid_uk
       ...

我想使用screen_name功能,为此,正在考虑使用SequenceMatcher获得结果来确定屏幕名称与实际名称的“接近”程度全名。

我正在尝试将以下函数应用于 FullnameScreen_Name 中的所有值,以便获得这两个功能的“相似”程度并添加将此分数添加到 DataFrame 的新列。

from difflib import SequenceMatcher

def similar(a, b):
    x = SequenceMatcher(None, a, b).ratio()
    score = x*100
    results = round(score, 2)
    return results

for column in dataframe:
    column[4] = similar(dataframe['Fullname'], dataframe['Screen_Name'])

dataframe.head(40)

我使用了 for 循环,因为我处理的数据不是很大。当我输入字符串时,该函数确实可以工作,但不幸的是,这似乎对我的 DataFrame 不起作用。

任何指向正确方向的指针将不胜感激。
非常感谢!

最佳答案

改为:

def similar(row):
    x = SequenceMatcher(None, row['FullName'], row['ScreenName']).ratio()
    score = x*100
    results = round(score, 2)
    return results

dataframe['result'] = dataframe.apply(lambda row: similar(row), axis=1)

关于python - 将函数应用于两个 DataFrame 列并从结果创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36631214/

相关文章:

django - 更新到 Django 1.8 - AttributeError : django. test.TestCase 没有属性 'cls_atomics'

python - 希望我的代码引发特定类型或错误,但打印原始错误

python - "Series objects are mutable and cannot be hashed"错误

Python 3+,读入文本文件并写入新文件(不包括行范围)

python-3.x - 使用 pandas 和 pyxlsb 以 xlsb 文件格式(Excel 二进制文件格式)写入输出

python - 应用条件分组

python - 返回 inf : how can I solve this? 的 pandas DataFrame 列的 mean()

python - ConvergenceWarning : Liblinear failed to converge, 增加迭代次数

python - 从字符串中获取所有可能的英文单词

python - 如何在我的服务器外查看 django 主页