簡體   English   中英

我可以在不必為每條記錄運行這些循環的情況下對這些記錄進行聚類嗎?

[英]Can I cluster these records without having to run these loops for every record?

所以我想對這張表中的記錄進行聚類,以找出哪些記錄是“相似的”(即有足夠的共同點)。 該表的示例如下:

        author beginpage endpage volume publication year  id_old  id_new
0          NaN       495     497    NaN             1975       1       1
1          NaN       306     317     14             1997       2       2
2        lowry       265     275    193             1951       3       3
3    smith p k        76      85    150             1985       4       4
4          NaN       248     254    NaN             1976       5       5
5     hamill p        85     100    391             1981       6       6
6          NaN      1513    1523      7             1979       7       7
7     b oregan       737     740    353             1991       8       8
8          NaN       503     517     98             1975       9       9
9      de wijs       503     517     98             1975       10      10

在這個小表中,最后一行的 'new_id' 應該等於 9,以表明這兩條記錄相似。

為了實現這一點,我編寫了下面的代碼,它適用於少量記錄。 但是,我想將我的代碼用於包含 15000 條記錄的表。 當然,如果您進行數學計算,使用此代碼將花費太長時間。 誰能幫助我使這段代碼更有效率? 提前致謝!

我的代碼,其中“dfhead”是包含記錄的表:

for r in range(0,len(dfhead)):
    for o_r in range(r+1,len(dfhead)):
        if ((dfhead.loc[r,c] == dfhead.loc[o_r,c]).sum() >= 3) :
            if (dfhead.loc[o_r,['id_new']] > dfhead.loc[r,['id_new']]).sum() ==1: 
                dfhead.loc[o_r,['id_new']] = dfhead.loc[r,['id_new']]

如果您只是想檢測“beginpage”、“endpage”、“volume”、“publication”、“year”之間的整體相等性,則應該嘗試處理重復項。 我不確定這一點,因為您的代碼對我來說仍然是一個謎。

這樣的事情可能會起作用(盡管您的列“id”首先需要在 dataframe 中命名為“id_old”):

cols = ["beginpage", "endpage","volume", "publication", "year"]

#isolate duplicated rows
duplicated = df[df.duplicated(cols, keep=False)]

#find the minimum key to keep
temp = duplicated.groupby(cols, as_index=False)['index'].min()
temp.rename({'id_old':'id_new'}, inplace=True, axis=1)

#import the "minimum key" to duplicated by merging the dataframes
duplicated = duplicated.merge(temp, on=cols, how="left")

#gather the "un-duplicated" rows
unduplicated = df[~df.duplicated(cols, keep=False)]

#concatenate both datasets and reset the index
new_df = unduplicated.append(duplicated)
new_df.reset_index(drop=True, inplace=True)

#where "id_new" is empty, then the data comes from "unduplicated"
#and you could fill the datas from id_old
ix = new_df[new_df.id_new.isnull()].index
new_df.loc[ix, 'id_new'] = new_df.loc[ix, 'id_old']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM