You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用Python将股票代码的市值打印列表转换为指定表头的DataFrame

Hey there! Let's fix this up so you get that clean DataFrame you're after. The key here is to collect the valid ticker-marketCap pairs as you iterate instead of just printing them, then convert that collection into a DataFrame. Here's how to adjust your code:

First, let's put all the pieces together (including your existing ticker-reading code):

import pandas as pd
from pandas_datareader import data as pdr
import yfinance as yf

# Step 1: Read tickers from your text file
with open("/Users/AB/OD/Earnings/tickers.txt") as fh:
    tick1 = fh.read().split()

# Step 2: Initialize an empty list to store valid data
valid_data = []

# Step 3: Iterate through tickers, collect market cap data
for ticker in tick1:
    try:
        # Extract the numeric market cap value (get_quote_yahoo returns a Series, so we grab the first element)
        market_cap = pdr.get_quote_yahoo(ticker)['marketCap'].iloc[0]
        # Add the ticker and its market cap to our list as a tuple
        valid_data.append( (ticker, market_cap) )
    except Exception as e:
        # Optional: Print failed tickers for debugging (remove if not needed)
        print(f"Skipping {ticker}: Could not retrieve market cap. Error: {str(e)}")
        pass

# Step 4: Convert the collected data to your target DataFrame
market_cap_df = pd.DataFrame(valid_data, columns=['ticker', 'marketCap'])

# Preview the result
print(market_cap_df)

What's improved here?

  • We use a valid_data list to store only successful (ticker, marketCap) pairs—this filters out any tickers that fail to return data automatically.
  • Added .iloc[0] to pull the actual numeric value from the Series returned by get_quote_yahoo—without this, your DataFrame would store Series objects instead of plain numbers.
  • Included an optional debug print to see which tickers are failing (helpful if you need to troubleshoot missing data).
  • Explicitly set the DataFrame column names to match your required ticker and marketCap headers.

This should give you a tidy, usable DataFrame with exactly the data you need. 😊

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

火山引擎 最新活动