【问题标题】:Call a report from a dictionary of dataframes从数据框字典中调用报告
【发布时间】:2021-01-01 16:04:00
【问题描述】:

我是我以前的question,我问过如何遍历多个 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

问候并感谢您的帮助!

【问题讨论】:

    标签: python pandas loops report


    【解决方案1】:
    data_dict = dict()  # create an empty dict here
    for k, df in df_dict.items():
        df_dict[k]['Return %'] = df.iloc[:, 0].pct_change(-1)*100
    
        # aggregate the max and min of Return
        mm = df_dict[k]['Return %'].agg(['max', 'min'])  
    
        # add it to the dict, with ticker as the key
        data_dict[k] = {'max': mm.max(), 'min': mm.min()}  
    
    # convert to a dataframe if you want
    mm_df = pd.DataFrame.from_dict(data_dict, orient='index')
    
    # display(mm_df)
              max      min
    aapl  8.70284 -4.90070
    msft  6.60377 -4.08443
    
    # save
    mm_df.to_csv('max_min_return.csv', index=True)
    

    【讨论】:

    • 再次,作为一个魅力工作!非常感谢特伦顿·麦金尼先生。祝您和您所爱的人一切顺利!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 2015-11-30
    相关资源
    最近更新 更多