Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k 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 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...