1 回答

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
添加回答
舉報