Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

Pandas/Python how to store store looped values

I am trying to loop multiple tickers into a function and I can print successfully the results however I cannot store them, only the last element is outputted. The loop seems overwrites the values generated earlier, can you please advise?

import yfinance as yf

y = ['SBUX', 'ICE']
b = {}

for x in y:
    ticker = yf.Ticker(x)
    d = ticker.get_info()
    for k, v in d.items():
        if k == 'zip' or k == 'sector' or k == 'symbol':
            b[k] = d[k]
    print(b)

result from the code:

{'zip': '98134', 'sector': 'Consumer Cyclical', 'symbol': 'SBUX'}
{'zip': '30328', 'sector': 'Financial Services', 'symbol': 'ICE'}

result if b is printed outside the code:

{'zip': '30328', 'sector': 'Financial Services', 'symbol': 'ICE'}

I would like to be able to print the 2 lines outside the code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can append them to a dataframe:

import yfinance as yf
import pandas as pd

new_df = pd.DataFrame()
y = ['SBUX', 'ICE']
b = {}

for x in y:
    ticker = yf.Ticker(x)
    d = ticker.get_info()
    for k, v in d.items():
        if k == 'zip' or k == 'sector' or k == 'symbol':
            b[k] = d[k]
    new_df = new_df.append(b, ignore_index=True)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...