![](/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.