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

如何用列表推导式在Pandas DataFrame中匹配股票代码获取对应市值?

Hey there! Let's break down your problem and fix those code snippets, plus cover the best approaches to get the market caps you need.

First, let's look at why your existing code isn't working:

  1. Your first attempt uses tickers['Symbol']==stocks_list — this doesn't work because == checks if each value in the Series is exactly equal to the entire list (which it never will be). You need isin() here instead.
  2. The second list comprehension has incorrect indexing: tickers['Symbol'][stock]['MarketCap'] is trying to index a Series with a stock ticker, which won't map to the right row.

Best Solutions

1. Optimized isin() Method (Most Efficient & Clean)

This is the standard pandas way to handle this kind of filter — it uses vectorized operations which are way faster than loops for large datasets:

import pandas as pd

tickers = pd.read_csv('NASDAQcompanylist.csv')
stocks_list = ['AAPL','GOOG']

# Filter rows where Symbol is in your list, extract MarketCap, convert to list
market_caps = tickers[tickers['Symbol'].isin(stocks_list)]['MarketCap'].tolist()
print(market_caps)  # Output: [85436200000000, 7001920000000] (example values)

This works because isin() returns a boolean Series marking which rows match your ticker list. We use that to filter the DataFrame, pull the MarketCap column, and convert it to a list with tolist().

2. Working List Comprehension (If You Prefer Loops)

Yes, you can use a list comprehension for this — you just need to correctly locate each ticker's row. Here are two ways:

Option A: Set Symbol as Index (Cleaner)

First, make Symbol the index of your DataFrame so you can directly look up rows by ticker:

tickers.set_index('Symbol', inplace=True)
market_caps = [tickers.loc[stock, 'MarketCap'] for stock in stocks_list]

Note: If there are duplicate ticker symbols in your data, loc will return a Series instead of a single value — you can add .iloc[0] to grab the first match if needed.

Option B: No Index Modification

If you don't want to change the original DataFrame, use boolean filtering inside the comprehension:

market_caps = [tickers[tickers['Symbol'] == stock]['MarketCap'].iloc[0] for stock in stocks_list]

Warning: This is less efficient than isin() because it runs a new filter for every ticker in your list — avoid this if you're working with large datasets.

3. Dictionary Mapping (For Repeated Queries)

If you need to look up market caps multiple times, create a ticker-to-cap dictionary first. This is the fastest method for repeated access:

# Create a dictionary mapping symbols to their market caps
symbol_cap_map = dict(zip(tickers['Symbol'], tickers['MarketCap']))

# Look up each ticker in your list
market_caps = [symbol_cap_map[stock] for stock in stocks_list]

If your stocks_list might have tickers not present in the DataFrame, use .get() to avoid KeyErrors:

market_caps = [symbol_cap_map.get(stock, None) for stock in stocks_list]

Quick Summary

  • Go with isin() for one-off queries — it's clean, pandas-idiomatic, and efficient.
  • Use a dictionary if you need to look up values multiple times.
  • List comprehensions work, but they're not the most efficient choice unless you have a specific reason to use them.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:26:55