![](/img/trans.png)
[英]How to count the values corresponding to each unique value in another column in a dataframe?
[英]How to count the unique values of a column and append each value to a dictionary?
本教程建議使用此解決方案
opened_file = open('AppleStore.csv')
from csv import reader
read_file = reader(opened_file)
apps_data = list(read_file)
content_ratings = {}
for row in apps_data[1:]:
c_rating = row[10] #the content rating that says which app is suitable for which age
if c_rating in content_ratings:
content_ratings[c_rating] += 1
else:
content_ratings[c_rating] = 1
print(content_ratings)
output 是
{'17+': 622, '4+': 4433, '9+': 987, '12+': 1155}
我只是想了解代碼邏輯。 該行說if c_rating in content_ratings:
應該返回False
因為它不滿足條件,因為content_rating
本身是空的,所以c_rating
不在字典中。 這個邏輯如何在字典中找到內容分級和 append?
if-else 語句中的兩行看起來相同,但略有不同, +
號:
if c_rating in content_ratings:
content_ratings[c_rating] += 1
else:
content_ratings[c_rating] = 1
content_ratings[c_rating] = 1
這是在 python 中將元素添加到字典中的方式。 您也可以以相同的方式更新現有的元素字典; 在這里content_ratings[c_rating] += 1
你得到了現有的元素並增加了它的價值。
所以,你是對的, if c_rating in content_ratings:
返回false
,它會添加元素,否則,它會更新它的值(增加計數)。
您可以在文檔中查看字典的基本操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.