python - 用数据框中给定的行索引替换列和行中的值
问题描述
我有一个 url 和经过验证的 url 的数据框,并添加了一个具有 levenstein 比率的列,它比较了每一行的两种类型的 url。
这是我的熊猫数据框的示例:
url url_ok2
13 10hanover.org/ NaN
15 111140.cevadosite.com/ aerorealestate.net/
42 18brownlow.com/ 18brownlow.com:443/
57 1granary.com/ 1granary.com/journal/
61 1rs.org.uk/ 1rs.io/
79 2020visionnetwork.eu/ network.crowdhelix.com/
这是我的脚本:
import Levenshtein as lev
to_test['lev_ratio'] = None
for i in range(to_test.shape[0]):
to_test.iloc[i]['lev_ratio'] = lev.ratio(str(to_test.iloc[i].url),str(to_test.iloc[i].url_ok2))
但是这些值不会被替换,请在运行脚本后查看数据框:url url_ok2 lev_ratio 13 10hanover.org/ NaN None 15 111140.cevadosite.com/ aerorealestate.net/ None 42 18brownlow.com/ 18brownlow.com:443/ None 57 1granary。 com/ 1granary.com/journal/ 无 61 1rs.org.uk/ 1rs.io/ 无 79 2020visionnetwork.eu/ network.crowdhelix.com/ 无
但是当我检查 lev.ratio(str(to_test.iloc[i].url),str(to_test.iloc[i].url_ok2)) 时,它给了我相应的值,即lev.ratio(str(to_test.iloc[0].url),str(to_test.iloc[0].url_ok2))
返回
0.45454545454545453
如何替换 lev_ratio 列中每一行的值?
解决方案
尝试使用.apply
数据框:
df['lev_ratio'] = df.apply(lambda x: lev.ratio(str(x.url),str(x.url_ok2)), axis=1)
推荐阅读
- node.js - Heroku/Express:尝试访问子路由时“未找到”(刷新时)
- php - Laravel 5.6 Redirect 和 Header 未从控制器内部重定向
- java - Thymeleaf 不将所有图标附加到模板
- javascript - 从 v-for v-if 组合调用 Vue 方法不返回值
- python - multiprocessing.dummy.Pool 中线程的本地对象
- arrays - 定义数量后的多维数组中的Powershell处理数组
- hadoop - gradle传递依赖冲突
- android - 已发布的私有应用在移动应用商店中不可见
- css - Angular 在没有复制/粘贴代码的情况下渲染一个或另一个模板
- r - 计算栅格的质心