从数据帧字典中调用报告

我问过如何迭代多个 csv 文件(例如 100 个不同的股票代码文件)并立即计算它们的每日收益。我想知道如何为每个文件调用这些返回的最大/最小值并打印报告。

以下是 Trenton McKinney 先生创建的词典:

import pandas as pd

from pathlib import Path


# create the path to the files

p = Path('c:/Users/<<user_name>>/Documents/stock_files')


# get all the files

files = p.glob('*.csv')


# created the dict of dataframes

df_dict = {f.stem: pd.read_csv(f, parse_dates=['Date'], index_col='Date') 

for f in files}


# apply calculations to each dataframe and update the dataframe

# since the stock data is in column 0 of each dataframe, use .iloc

for k, df in df_dict.items():

    df_dict[k]['Return %'] = df.iloc[:, 0].pct_change(-1)*100

问候并感谢您的帮助!



侃侃尔雅
浏览 77回答 1
1回答

米脂

data_dict = dict()&nbsp; # create an empty dict herefor k, df in df_dict.items():&nbsp; &nbsp; df_dict[k]['Return %'] = df.iloc[:, 0].pct_change(-1)*100&nbsp; &nbsp; # aggregate the max and min of Return&nbsp; &nbsp; mm = df_dict[k]['Return %'].agg(['max', 'min'])&nbsp;&nbsp;&nbsp; &nbsp; # add it to the dict, with ticker as the key&nbsp; &nbsp; data_dict[k] = {'max': mm.max(), 'min': mm.min()}&nbsp;&nbsp;# convert to a dataframe if you wantmm_df = pd.DataFrame.from_dict(data_dict, orient='index')# display(mm_df)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; max&nbsp; &nbsp; &nbsp; minaapl&nbsp; 8.70284 -4.90070msft&nbsp; 6.60377 -4.08443# savemm_df.to_csv('max_min_return.csv', index=True)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python