1 回答
![?](http://img1.sycdn.imooc.com/54584e1f0001bec502200220-100-100.jpg)
TA贡献1877条经验 获得超1个赞
我认为数据的最佳选择是将文件读入数据帧字典中。
使用
pathlib
和.glob
创建所有文件的列表使用字典理解来创建数据帧的字典。
字典可以按照字典的标准方式进行迭代,使用
dict.items()
.df_dict[k]
对每个数据帧进行寻址,其中k
是字典键,即文件名。从你的上一个问题来看,我希望
.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
添加回答
举报