我有一個包含大約 270,000 本書的 DataFrame,我想根據 獲取_dummies Book-Title,但只使用選定數量的單詞。最后,我想使用 200-300 個真正有區別的詞,比如“神秘”、“謀殺”、“經典”和“科學”,看看它們是否在Book-Title每本書中。我想要為這些單詞中的每一個創建一列,如果未找到該單詞則填充為 0,如果找到則填充為 1。
如果我嘗試獲取整個列的get_dummies ,我最終會得到數十萬個不同的列,而且我沒有 RAM 來進行這種處理。
下面是我想要的一個例子。我已經有一個書名中最常用的 200 個單詞的串列,我只是不知道如何從這個串列中制作列。
輸入:
ISBN Book-Title Book-Author Year-Of-Publication Publisher
0 0195153448 Classical Mythology Mark P. O. Morford 2002 Oxford University Press
1 0002005018 Clara Callan Richard Bruce Wright 2001 HarperFlamingo Canada
2 0060973129 Decision in Normandy Carlo D Este 1991 HarperPerennial
3 0374157065 Flu: The Story of the Great... Gina Bari Kolata 1999 Farrar Straus Giroux
4 0393045218 The Mummies of Urumchi E. J. W. Barber 1999 W. W. Norton & Company
期望的輸出:
ISBN Title 'World' 'Mythology' 'Mystery' 'Mummies'
0 0195153448 Classical Mythology 0 1 0 0
1 0002005018 Clara Callan 0 0 0 0
2 0060973129 Decision in Normandy 0 0 0 0
3 0374157065 Flu: The Story of the Great... 0 0 0 0
4 0393045218 The Mummies of Urumchi 0 0 0 1
先感謝您!
亞當
uj5u.com熱心網友回復:
您可以使用 for 回圈并遍歷關鍵字串列,為每個關鍵字創建一個新列。請記住,您可能希望將小寫單詞與小寫單詞進行比較,以免大小寫成為問題。
df = pd.DataFrame({'Title': ['Classical Mythology','Clara Callan', 'Decision in Normandy', 'Flu: The Story of the Great...', 'The Mummies of Urumchi']})
for keyword in ['World','Mythology','Mystery','Mummies']:
df[keyword] = df['Title'].apply(lambda x: 1 if keyword.lower() in x.lower() else 0)
結果:
>>> df
Title World Mythology Mystery Mummies
0 Classical Mythology 0 1 0 0
1 Clara Callan 0 0 0 0
2 Decision in Normandy 0 0 0 0
3 Flu: The Story of the Great... 0 0 0 0
4 The Mummies of Urumchi 0 0 0 1
uj5u.com熱心網友回復:
您可以將一個函式應用于'Book-Title'遍歷單詞串列的列,以檢查每個條目中是否存在每個單詞;并將輸出轉換為 DataFrame:
lst = ['World', 'Mythology', 'Mystery', 'Mummies']
df[lst] = df['Book-Title'].apply(lambda x: pd.Series([int(w in x) for w in lst]))
輸出:
Book-Title World Mythology Mystery Mummies
0 Classical Mythology 0 1 0 0
1 Clara Callan 0 0 0 0
2 Decision in Normandy 0 0 0 0
3 Flu: The Story of the Great 0 0 0 0
4 The Mummies of Urumchi 0 0 0 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/383789.html
