python - 如何根据在主数据集中找到多少重复项来创建其值扩展的字典?
问题描述
我正在使用的数据集可以在这里找到:https ://www.kaggle.com/lava18/google-play-store-apps 这个数据集有两列对应用程序的类型进行分类(第 1 列和第 9 列 - 我开始计算从第一列为 0)。也许下面的图片会有所帮助:
来自第 1 列的数据粒度小于第 9 列,因此字典键将是 Column1 而值 Column9。我已经有了一个函数来查看第 1 列到第 9 列中每个类别的百分比是多少。
def freq_table(dataset, index_category):
table = {}
total = 0
for row in dataset:
total += 1
category = row[index_category]
if category in table:
table[category] += 1
else:
table[category] = 1
table_percentages = {}
cat_num=0
for key in table:
cat_num+=1
percentage = (table[key] / total) * 100
table_percentages[key] = percentage
print(f'Total Number of Categories: {cat_num}')
return table_percentages
#Removing from being a dictionary and putting in a Descending Order
def display_table(dataset, index_category):
table = freq_table(dataset, index_category)
table_display = []
for key in table:
key_val_as_tuple = (table[key], key)
#The order of this sentence is - Percentage and Category, because the function sorted gets the first element to sort it
#And this is the Percentage since we want a Descending Order
#This is a Tuple since we will not need to change these values and it is easy to pack values together
table_display.append(key_val_as_tuple)
#In order to pack everything in one object, we use List Append (Tuples don't have Append)
table_sorted = sorted(table_display, reverse = True) #We choose the Descending Order in the Percentage Field here
for entry in table_sorted:
print(entry[1], ':', entry[0], '%')
#Before the order was Percentage : Category, now to be more user friendly we change to Category : Percentage
但是我如何创建一个可以告诉我以下内容的函数?
家庭(第 0 列)具有类型(第 9 列):“休闲;脑力游戏”占 35%,“教育;创意”占 20%,“教育;教育”占 45%
如果需要任何进一步的信息,请告诉我,非常感谢您的帮助。 '
解决方案
它更好地pandas
用于给定的文件。pandas 将以表格格式读取文件,并且将提供许多分组选项 -
import pandas as pd
x = pd.read_csv("googleplaystore.csv")
x = x.groupby(["Category", "Genres"], as_index=False)[['App']].count().rename(columns={'App' : 'cnt'})
x_tot = x.groupby(["Category"], as_index=False)[['cnt']].sum().rename(columns={'cnt' : 'tot'})
x = x.merge(x_tot, on = ['Category'])
x['pct'] = x['cnt']/x['tot']
推荐阅读
- oop - 创建对象数组时如何初始化对象的属性?
- ios - 在 Storyboard 中按住 Control 并拖动 UIView 以呈现控制器?
- json - 如何在 Elm 中对简单的自定义类型进行编码和解码?
- makefile - 如何防止make重新生成.gitignore?
- html - 如何在不使用其他 html 文件的情况下更新页面中的内容
- perl - Perl:确定键是否在哈希中的意外结果
- firebase - 在 firebase 函数中处理 webhook 时如何进行经过身份验证的 Firestore 查询?
- javascript - 如果条件未按预期工作,则 AJAX 调用,进一步阻止其他条件
- go - 当通道接收到新值时无限循环被终止
- c# - 后期操作中的 ViewModel 为空