首页 > 解决方案 > 如何根据在主数据集中找到多少重复项来创建其值扩展的字典?

问题描述

我正在使用的数据集可以在这里找到: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%

如果需要任何进一步的信息,请告诉我,非常感谢您的帮助。 '

标签: pythonlistfunctiondictionaryjupyter-notebook

解决方案


它更好地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']

推荐阅读