首页 > 解决方案 > 用数据框中给定的行索引替换列和行中的值

问题描述

我有一个 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 列中每一行的值?

标签: pythonpandas

解决方案


尝试使用.apply数据框:

df['lev_ratio'] = df.apply(lambda x: lev.ratio(str(x.url),str(x.url_ok2)), axis=1)


推荐阅读