[英]What's the difference between these two ways of implementing `on duplication increment`?
[英]What's the difference between these two ways to calculate the number of occurrences of two words in a text column?
我是 pandas 的新手,我現在正在 Kaggle 上學習它。
這是一個練習,詢問在description
列中查找兩個單詞的出現次數。
我從 StackOverflow 中找到了第一條語句,但第二條是正確答案。 造成這種不同結果的原因是什么?
tropical = reviews.description.str.count("tropical").sum()
fruity = reviews.description.str.count("fruity").sum()
descriptor_counts = pd.Series([tropical,fruity])
`
tropical = reviews.description.map(lambda desc: 'tropical' in desc).sum()
fruity = reviews.description.map(lambda desc: 'fruity' in desc).sum()
descriptor_counts = pd.Series([tropical, fruity],index=['tropical','fruity'])
第一個結果是[3703, 9259]
第二個結果是[3607, 9090]
更新:原來的問題是。 創建一個系列descriptor_counts,計算這兩個單詞中的每一個出現在數據集的描述列中的次數。
第一個是少,因為它是唯一獲得該是值'tropical'
或'fruity'
。
所以:
>>> s='a'
>>> s=='a'
True
但是第二個是獲取包含'tropical'
或'fruity'
,所以上面的:
>>> s='ab'
>>> s=='a'
False
所以它這樣做:
>>> s='ab'
>>> 'a' in s
True
這是一個例子
第一個代碼將tropical 計數為5,fruity 計數為4。它計算同一描述中單詞的重復次數。 因此,在此示例中,結果將是[5,4]
。
第二個代碼將主題計算為 4,水果計算為 3。它計算每個描述中單詞的存在( if tropical in description
)。 一旦找到它,無論描述中有多少,它都算作一個。 所以,結果將是[4,3]
。
所以,我覺得這個問題是錯誤的。 如果問題是關於兩個單詞的出現次數,則在此示例中[5,4]
應該是正確的(在您的情況下為[3703,9259]
)。 如果問題詢問每個單詞出現多少個描述,那么您正在使用if word in description
。 所以,再檢查一遍問題。
count1, count2 = 0, 0
for i in description.iteritems():
if "fruity" in i[0]:
count1 += i[1]
if "tropical" in i[0]:
count2 += i[1]
descriptor_counts = pd.Series(data = {"fruity": count1, "tropical": count2},
index = ["tropical", "fruity"])
最近我遇到了同樣的問題,這將是我不使用“lambda 表達式”的解決方案
這就是我可以解決它並得到正確答案的方法:
n_trop = reviews['description'].str.contains('tropical').sum()
n_fruit = reviews['description'].str.contains('fruity').sum()
descriptor_counts = pd.Series([n_trop,n_fruit], index=('tropical','fruity'))
print(descriptor_counts)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.