简体   繁体   English

在循环中创建多个 Pandas 数据帧

[英]Creating Multiple Pandas Data Frames in a loop

Trying to create a pandas data frame for each stock ticker in a list尝试为列表中的每个股票代码创建一个熊猫数据框

My Code:我的代码:

for ticker in stock_tickers:
   
     data = pd.read_csv(f'{ticker}_{get_date()}.csv')

it will only create one pandas data frame for the last stock ticker... is there anyway for this to be done all of them?它只会为最后一个股票行情创建一个 Pandas 数据框......无论如何都要完成所有这些?

You end up with only one data set because the data variable gets overwritten on every step of the loop.您最终只有一个数据集,因为data变量在循环的每一步都会被覆盖。

You could store your data in a dictionary (assuming here that ticker is a string):您可以将数据存储在字典中(假设这里的ticker是一个字符串):

data = {}

for ticker in stock_tickers:
    data[ticker] = pd.read_csv(f'{ticker}_{get_date()}.csv')

More compact version using a dict comprehension:使用字典理解的更紧凑版本:

data = {ticker: pd.read_csv(f'{ticker}_{get_date()}.csv')
        for ticker in stock_tickers}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM