首页 > 解决方案 > 如何创建一个列来告诉我一个数字出现的次数?

问题描述

from bs4 import BeautifulSoup
import requests
import pandas as pd
import ast

s = requests.Session()

page=1
traits = []

#Get URL and extract content
class Scraper():

    while page != 10:
        content = s.get('https://bullsontheblock.com/api/tokens/{}'.format(page))
        soup = BeautifulSoup(content.text, 'html.parser')
        page = page + 1
    
        traits = ast.literal_eval(soup.text)['attributes']

        df = pd.DataFrame(traits).set_index('value').to_numpy()
        trait_count = len(df)
    
        print(trait_count)

每当我使用上面的代码时,我都会得到用行分隔的整数,如下所示:

9
8
8
8
6
9
8
8
7

如何创建一个列来告诉我一个数字出现的次数,所以它看起来像这样:

9 - 2
8 - 5
7 - 1
6 - 1

基本上,上面的代码提取了一个列表中有多少特征的计数,但是我有多个列表,所以我想提取具有一定数量特征的列表出现的次数,这样它就可以看起来像上面那样。我该怎么做?

标签: pythonpython-3.xpandas

解决方案


将每个数字添加到一个字符串中,然后计算每个数字的频率

nums = "988869887"
fre = {}

for num in nums:
    if num in fre:
        fre[int(num)] += 1
    else:
        fre[int(num)] = 1

print(fre)

输出 {9: 2, 8: 5, 6: 1, 7: 1}


推荐阅读