python 空间无限制结果,连接2列时出错

ruyhziif  于 2022-11-27  发布在  Python
关注(0)|答案(1)|浏览(136)

我正在运行的代码给出的结果是空间消除的。这给我的部门列带来了问题,该列给出的结果是Communication Services。它为Communication创建了1列,为Services创建了另一列,而我需要1列表示Communication Services。我曾尝试将这2列连接为1列,但遇到属性和字符串错误,不知道如何实现。有谁能演示一下如何做到这一点吗?谢谢
编码

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

list_of_futures= []

def get_stats(ticker):
    info = yf.Tickers(ticker).tickers[ticker].info
    s= f"{ticker} {info['currentPrice']} {info['marketCap']} {info['sector']}"
    
    list_of_futures.append(s)

ticker_list = ['AAPL', 'ORCL', 'GTBIF', 'META']

with ThreadPoolExecutor() as executor:
    executor.map(get_stats, ticker_list)
    
(
    pd.DataFrame(list_of_futures)
        [0].str.split(expand=True)
        .rename(columns={0: "Ticker", 1: "Price", 2: "Market Cap", 3: "Sector", 4: "Sector1"})
        .to_excel("yahoo_futures.xlsx", index=False)
)

当前结果

预期结果

u0njafvf

u0njafvf1#

让我们重新定义get_stats函数,使其返回字典而不是字符串。

def get_stats(ticker):
    info = yf.Tickers(ticker).tickers[ticker].info
    cols = ['currentPrice', 'marketCap', 'sector']
    return {'ticker': ticker, **{c: info[c] for c in cols}}

tickers = ['AAPL', 'ORCL', 'GTBIF', 'META']

with ThreadPoolExecutor() as executor:
    result_iter = executor.map(get_stats, tickers)

df = pd.DataFrame(result_iter)

测试结果

ticker  currentPrice      marketCap                  sector
0   AAPL        148.11  2356148699136              Technology
1   ORCL         82.72   223027183616              Technology
2  GTBIF         13.25     3190864896              Healthcare
3   META        111.41   295409188864  Communication Services

相关问题