【问题标题】:Pandas/Python how to store store looped valuesPandas/Python 如何存储循环值
【发布时间】:2021-04-17 13:51:10
【问题描述】:

我正在尝试将多个代码循环到一个函数中,我可以成功打印结果,但是我无法存储它们,只输出最后一个元素。循环似乎覆盖了之前生成的值,您能建议吗?

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)

代码结果:

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

如果 b 打印在代码之外的结果:

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

我希望能够打印代码外的 2 行

【问题讨论】:

    标签: python pandas loops dictionary


    【解决方案1】:

    您可以将它们附加到数据框:

    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)
    

    【讨论】:

    • 您好,谢谢,但是我收到以下消息: ValueError: If using all scalar values, you must pass an index
    • 感谢它的工作!你知道为什么使用列表而不是数据框不起作用吗?
    • 因为您从每次循环运行开始创建字典。您需要将其附加到数组或数据框(如我的解决方案)
    猜你喜欢
    • 2021-10-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多