ipython Pandas : How can I compare different rows of one column with Levenshtein distance metric?

萝らか妹 提交于 2019-12-14 02:19:24

问题


I have a table like this:

id name
1  gfh
2 bob
3 boby
4 hgf

etc.

I am wondering how can I use Levenshtein metric to compare different rows of my 'name' column?

I already know that I can use this to compare columns:

L.distance('Hello, Word!', 'Hallo, World!')

But how about rows? Can anybody help?


回答1:


Here is a way to do it with pandas and numpy:

from numpy import triu, ones
t = """id name
1 gfh
2 bob
3 boby
4 hgf"""

df = pd.read_csv(pd.core.common.StringIO(t), sep='\s{1,}').set_index('id')
print df

        name
id      
1    gfh
2    bob
3   boby
4    hgf

Create dataframe with list of strings to mesure distance:

dfs = pd.DataFrame([df.name.tolist()] * df.shape[0], index=df.index, columns=df.index)
dfs = dfs.applymap(lambda x: list([x]))
print dfs

    id      1      2       3      4
id                             
1   [gfh]  [bob]  [boby]  [hgf]
2   [gfh]  [bob]  [boby]  [hgf]
3   [gfh]  [bob]  [boby]  [hgf]
4   [gfh]  [bob]  [boby]  [hgf]

Mix lists to form a matrix with all variations and make upper right corner as NaNs:

dfd = dfs + dfs.T
dfd = dfd.mask(triu(ones(dfd.shape)).astype(bool))
print dfd

id            1            2            3    4
id                                            
1           NaN          NaN          NaN  NaN
2    [gfh, bob]          NaN          NaN  NaN
3   [gfh, boby]  [bob, boby]          NaN  NaN
4    [gfh, hgf]   [bob, hgf]  [boby, hgf]  NaN

Measure L.distance:

dfd.applymap(lambda x: L.distance(x[0], x[1]))



回答2:


Maybe by comparing each value one to the other and storing the whole combination results.

Naively coded, something like

input_data = ["gfh", "bob", "body", "hgf"]
data_len = len(input_data)
output_results = {}

for i in range(data_len):
    word_1 = input_data[i]
    for j in range(data_len):
        if(j == i): #skip self comparison
            continue
        word_2 = input_data[j]
        #compute your distance
        output_results[(word_1, word_2)] = L.distance(word_1, word_2)

And then do what you want with output_results



来源:https://stackoverflow.com/questions/29429509/ipython-pandas-how-can-i-compare-different-rows-of-one-column-with-levenshtein

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!