【问题标题】:How can I create a Dictionary that has its Values expanding depending of how many duplicates is found on the main Dataset?如何根据在主数据集中找到多少重复项来创建其值扩展的字典?
【发布时间】:2020-09-20 18:00:23
【问题描述】:

我使用的数据集可以在这里找到:https://www.kaggle.com/lava18/google-play-store-apps 该数据集有两列对 App 的类型进行分类(第 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%

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

【问题讨论】:

    标签: python list function dictionary jupyter-notebook


    【解决方案1】:

    给定文件最好使用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']
    

    【讨论】:

      猜你喜欢
      • 2018-04-07
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 2020-04-16
      • 2020-12-04
      • 2020-06-21
      • 2019-02-23
      相关资源
      最近更新 更多