You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python爬取加密货币的输出保存为DataFrame或变量

问题:如何将加密货币列表数据赋值给变量或转换为DataFrame

你现在的代码只是直接打印数据,要把这些内容保存下来供后续使用,核心是先收集数据到容器(比如列表),再转成需要的格式,以下是具体实现:

解决方案代码

import time
import requests
import pandas as pd  # 需要导入pandas库,未安装可执行 pip install pandas

url = "https://web-api.coinmarketcap.com/v1/cryptocurrency/listings/latest"

# 创建空列表用来存储所有数据
crypto_data = []

for start in range(1, 20000, 5000):
    params = {
        'start': start,
        'limit': 5000,
    }

    r = requests.get(url, params=params)
    data = r.json()
    
    for number, item in enumerate(data['data']):
        # 把需要的字段以字典形式添加到列表,替代直接打印
        crypto_data.append({
            'rank': start + number,
            'symbol': item['symbol'],
            'date_added': item['date_added'][:10]
        })

# 转换为DataFrame
crypto_df = pd.DataFrame(crypto_data)

# 现在crypto_data是存储所有数据的列表,crypto_df是DataFrame,均可作为后续函数的输入
print(crypto_df.head())  # 查看前5条数据示例

关键说明

  1. 为什么str()只得到最后一条数据?
    你之前应该是每次循环都把当前数据赋值给同一个变量(比如result = str(...)),这样变量会被循环反复覆盖,最终仅保留最后一次循环的内容。而用列表append是累加存储所有数据,不会出现覆盖问题。

  2. 两种使用场景

    • 若只需一个可迭代的数据源,crypto_data这个列表可直接用于后续函数;
    • 若要做数据分析、筛选、排序等操作,crypto_df这个DataFrame会更便捷。

内容的提问来源于stack exchange,提问作者pommepilling

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 07:25:14