python - 如何将多个文件作为单独的数据框读取并在列上执行计算?
问题描述
我正在计算单个股票收益如下:
data = pd.read_csv(r'**file**.csv')
data.index = data.Date
data['Return %'] = data['AAPL'].pct_change(-1)*100
data
输出:
Date AAPL Return %
Data
2020-09-11 2020-09-11 56.00 0.000000
2020-09-10 2020-09-10 56.00 -3.879162
2020-09-09 2020-09-09 58.26 2.138850
2020-09-08 2020-09-08 57.04 -2.211555
2020-09-04 2020-09-04 58.33 0.882048
2020-09-03 2020-09-03 57.82 -3.585126
2020-09-02 2020-09-02 59.97 -0.133222
现在,我保存了许多其他 csv 文件作为股票符号,我想使用这些符号中的每一个来执行上述相同的计算。最重要的是,我想打印一份报告,说明每个品种回报的最佳日期。
如果需要更多详细信息,请告诉我。
提前致谢!
解决方案
- 我认为您的数据的最佳选择是将文件读入数据框字典。
- 使用
pathlib
和.glob
创建所有文件的列表 - 使用字典理解来创建数据帧的字典。
- 使用
- 字典可以以字典的标准方式迭代,使用
dict.items()
. df_dict[k]
寻址每个数据帧,其中k
dict 键是文件名。- 从你的最后一个问题来看,我希望
.csv
文件用一Date
列而不是两列读入。 - 每个文件的数字数据应位于索引 0 的列中,之后
Date
设置为索引。- 由于每个文件的列名都不同,因此最好使用
.iloc
该列来寻址。 :
表示所有行,0
是数值数据的列索引。
- 由于每个文件的列名都不同,因此最好使用
df_dict.keys()
将返回所有键的列表- 使用 单独访问数据框
df_dict[key]
。
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
推荐阅读
- r - 如何从箱线图中提取和格式化中位数和 IQR
- r - 如何在矩阵上使用 which() 来获取唯一索引
- java - 从列表创建 HashMap
- mysql - 为什么从 mysql 获取输出时这个 bash 变量是空白的?
- javascript - 用于服务器端渲染的 NodeJS 路由
- mysql - 如何删除时间戳比现在旧的行?
- java - 在junit4中产生故障
- c - linux stat函数中struct stat * buffer和&buffer有什么区别
- php - 如何将 Session 变量从经典 php 文件传递到 CakePHP 文件?
- python - 为什么 numpy 的 where 操作比 apply 函数快?