大家早上好,我有一個資料框,其中一列由串列組成:
import pandas as pd
df = pd.DataFrame({'Ind':['A','B','C','D'],'lists':[['dog','cat','horse','squirrel','bird'],
['dog','horse','fish','whale'],
['moose','cat','squirrel','ant','chicken'],
['dog','moose','cat','bird','ant']]})
我想要實作的是一個叉積矩陣,其中我有一個每個串列對之間的“相似性”索引(當它們相同時為 0,如果它們沒有任何共同元素,則為 1)。我使用的 rn 是一個簡單的遞回,它已經完成了作業,但是當資料框維度增加時當然會遇到困難:
list_tot = []
for i in range(len(df)):
list_temp = []
for j in range(len(df)):
list1 = df.iloc[i]['lists']
list2 = df.iloc[j]['lists']
minlist = min(len(list1),len(list2))
dis = (minlist - len([el for el in list1 if el in list2]))/minlist
list_temp.append(dis)
list_tot.append(list_temp)
現在的輸出是一個串列串列,但可以是任何東西。
[[0.0, 0.5, 0.6, 0.4],
[0.5, 0.0, 1.0, 0.75],
[0.6, 1.0, 0.0, 0.4],
[0.4, 0.75, 0.4, 0.0]]
我也知道輸出矩陣是對稱的,所以我可以只計算 (N * (N 1)) / 2 相似度而不是 N ** 2,但我不確定如何得到相同的輸出。
非常感謝您提前。
uj5u.com熱心網友回復:
您可以使用itertools.combinations自定義函式來計算相似度(這里使用 1 - jaccard 相似度,您可以使用任何將 2 個串列作為輸入并回傳浮點數的函式),然后有點麻木的魔法:
import numpy as np
from itertools import combinations
def similarity(l1, l2):
s1 = set(l1)
s2 = set(l2)
return 1 - len(s1&s2)/len(s1|s2)
a = np.zeros((len(df), len(df)))
a[np.triu_indices(len(df), k=1)] = [similarity(a,b) for a,b in combinations(df['lists'], r=2)]
a = a.T
np.fill_diagonal(a, 1)
out = pd.DataFrame(a, index=df['Ind'], columns=df['Ind'])
print(out)
輸出:
Ind A B C D
Ind
A 0.000000 0.714286 0.750000 0.571429
B 0.714286 0.000000 1.000000 0.875000
C 0.750000 1.000000 0.000000 0.571429
D 0.571429 0.875000 0.571429 0.000000
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/519485.html
上一篇:在apandas資料框中連接字串
下一篇:熊貓系列墊功能不適用于熊貓應用
