将列表作为行添加到 DataFrame

问题描述 投票:0回答:1

我有一个程序,它调用 yfinance 来获取股票代码列表的一些股票数据。我使用 ThreadPoolExecutor 处理 yfinance 调用,并为每个代码返回一个数据列表。

#!/usr/bin/env python
import sys
import yfinance as yf
from concurrent.futures import ThreadPoolExecutor
import pandas as pd

def get_stats(ticker):
    info = yf.Tickers(ticker).tickers[ticker].info
    data = [ticker, info['volume']/info['floatShares'], info['floatShares']]
    return data

ticker_list = sys.argv[1:]
ticker_list = ['AAPL', 'AMZN', 'GOOG']
ticker_list = [item.upper() for item in ticker_list]

table_title = ['Symbol', 'FTR', 'Float']
df = pd.DataFrame(columns = table_title)

with ThreadPoolExecutor() as executor:
    results = list(executor.map(get_stats, ticker_list))
    df.loc[len(df)] = results

print(df)

当我执行上面的代码时,我得到以下输出:

                                      Symbol                                       FTR                                       Float
0  [AAPL, 0.003960062654206358, 15179506298]  [AMZN, 0.006952834770567285, 9360261411]  [GOOG, 0.0029524428963116282, 10942799280]

检查此处找到的建议https://stackoverflow.com/a/48440126/21926611我不确定为什么我得到上述输出而不是所需的输出

   Symbol FTR                   Float
0  AAPL   0.003960062654206358  15179506298
1  AMZN   0.006952834770567285  9360261411
2  GOOG   0.0029524428963116282 10942799280
python pandas dataframe
1个回答
0
投票

您的代码将整个

results
列表添加到每一行。您需要添加
results
列表中的每个单独项目。

import sys
import yfinance as yf
from concurrent.futures import ThreadPoolExecutor
import pandas as pd

def get_stats(ticker):
    info = yf.Tickers(ticker).tickers[ticker].info
    data = [ticker, info['volume']/info['floatShares'], info['floatShares']]
    return data

ticker_list = sys.argv[1:]
ticker_list = ['AAPL', 'AMZN', 'GOOG']
ticker_list = [item.upper() for item in ticker_list]

table_title = ['Symbol', 'FTR', 'Float']
df = pd.DataFrame(columns = table_title)

with ThreadPoolExecutor() as executor:
    results = list(executor.map(get_stats, ticker_list))
    # Adds items from results
    for result in results:
      df.loc[len(df)] = result

print(df)
© www.soinside.com 2019 - 2024. All rights reserved.