[英]Grouping data in a dataframe to produce lists against unique ids in Pandas/Python
[英]Produce unique ids for a list of lists with words
我有成對單詞的列表列表,並想要在ids上描述單詞。 Ids應該是從0到len(set(words))。 該列表現在看起來像這樣:
[['pluripotent', 'Scharte'],
['Halswirbel', 'präventiv'],
['Kleiber', 'Blauspecht'],
['Kleiber', 'Scheidung'],
['Nillenlutscher', 'Salzstangenlecker']]
結果應該具有相同的格式,但使用id。 例如:
[[0, 1],
[2, 3],
[4, 5],
[4, 6],
[7, 8]]
我到現在為止,但它沒有給我正確的輸出:
def words_to_ids(labels):
vocabulary = []
word_to_id = {}
ids = []
for word1,word2 in labels:
vocabulary.append(word1)
vocabulary.append(word2)
for i, word in enumerate(vocabulary):
word_to_id [word] = i
for word1,word2 in labels:
ids.append([word_to_id [word1], word_to_id [word1]])
print(ids)
輸出:
[[0, 0], [2, 2], [6, 6], [6, 6], [8, 8]]
它是重復的ids,其中有獨特的單詞。
你有兩個錯誤。 首先,你有一個簡單的拼寫錯誤,在這里:
for word1,word2 in labels:
ids.append([word_to_id [word1], word_to_id [word1]])
你在那里兩次添加word1
的id。 糾正第二個word1
來查找word2
。
接下來,你沒有測試你之前是否看過一個單詞,所以對於'Kleiber'
你首先給它id 4
,然后在下一次迭代時用6
覆蓋那個條目。 您需要提供唯一的單詞數字,而不是所有單詞:
counter = 0
for word in vocabulary:
if word not in word_to_id:
word_to_id[word] = counter
counter += 1
或者如果你已經列出了這個單詞,你就不能在vocabulary
添加單詞。 順便說一下,你真的不需要一個單獨的vocabulary
表。 一個單獨的循環不會給你帶來任何東西,所以以下工作原理:
word_to_id = {}
counter = 0
for words in labels:
for word in words:
word_to_id [word] = counter
counter += 1
您可以使用defaultdict
對象和itertools.count()
提供默認值來簡化代碼:
from collections import defaultdict
from itertools import count
def words_to_ids(labels):
word_ids = defaultdict(count().__next__)
return [[word_ids[w1], word_ids[w2]] for w1, w2 in labels]
每次調用__next__
, count()
對象都會為您提供系列中的下一個整數值,而defaultdict()
將在每次嘗試訪問字典中尚不存在的鍵時調用它。 它們共同確保每個唯一單詞的唯一ID。
有兩個問題:
word_to_id
重復查找word1
來制作拼寫錯誤。 word_to_id
字典時,您只需要考慮唯一值。 例如,在Python 3.7+中,您可以利用插入順序的詞典:
for i, word in enumerate(dict.fromkeys(vocabulary)):
word_to_id[word] = i
for word1, word2 in labels:
ids.append([word_to_id[word1], word_to_id[word2]])
3.7之前版本的替代方法是使用collections.OrderedDict
或itertools
unique_everseen
配方 。
如果沒有訂購要求,您可以使用set(vocabulary)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.