Python循环自动创建独立DataFrame并设置时间索引求助
Hey there! I see exactly where your loop is going off track. Let's break this down and fix it step by step.
问题根源
Your current code is storing each ticker's raw dictionary list directly as a column in a single data DataFrame. That's why you can't access data[t]['time'] properly—each column is just a list of dictionaries, not a structured DataFrame with columns like time, close, etc.
解决方案
Instead of shoving everything into one DataFrame's columns, we'll use a dictionary to store individual DataFrames for each ticker. This keeps each ticker's data isolated and lets you work with them properly.
修正后的代码
import requests import pandas as pd desired_width = 320 pd.set_option('display.width', desired_width) # 用字典存储每个ticker的DataFrame,而不是单个DataFrame crypto_data = {} tickers = ['BTC', 'ETH', 'XRP'] for t in tickers: url = f'https://min-api.cryptocompare.com/data/histoday?fsym={t}&tsym=USD&limit=600000000000&aggregate=1&e=CCCAGG' response = requests.get(url) # 把JSON数据直接转换成DataFrame,而不是存在列里 df = pd.DataFrame(response.json()['Data']) # 转换时间列并设置为索引 df['time'] = pd.to_datetime(df['time'], unit='s') df.set_index('time', inplace=True) # 把处理好的DataFrame存入字典 crypto_data[t] = df print(f"Downloading data for: {t}") print(f"Sample data for {t}:\n", df.head(5), "\n")
代码说明
- We use a dictionary
crypto_datawhere each key is a ticker (like 'BTC') and the value is its dedicated DataFrame. - Converting
response.json()['Data']directly to a DataFrame gives us proper columns (time,close,high, etc.) right away. pd.to_datetime(df['time'], unit='s')converts the Unix timestamp to a readable datetime format.df.set_index('time', inplace=True)sets the datetime column as the index, which is perfect for time-series data.
怎么访问单个ticker的数据
After running the loop, you can access each ticker's DataFrame like this:
# 获取BTC的数据 btc_df = crypto_data['BTC'] print(btc_df.describe()) # 获取ETH的收盘价 eth_close_prices = crypto_data['ETH']['close']
This way, each ticker's data is properly structured and ready for analysis!
内容的提问来源于stack exchange,提问作者Giladbi

