1 回答

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超1個(gè)贊
我認(rèn)為數(shù)據(jù)的最佳選擇是將文件讀入數(shù)據(jù)幀字典中。
使用
pathlib
和.glob
創(chuàng)建所有文件的列表使用字典理解來(lái)創(chuàng)建數(shù)據(jù)幀的字典。
字典可以按照字典的標(biāo)準(zhǔn)方式進(jìn)行迭代,使用
dict.items()
.df_dict[k]
對(duì)每個(gè)數(shù)據(jù)幀進(jìn)行尋址,其中k
是字典鍵,即文件名。從你的上一個(gè)問(wèn)題來(lái)看,我希望
.csv
用一列而不是兩列讀入文件Date
。每個(gè)文件的數(shù)字?jǐn)?shù)據(jù)應(yīng)位于索引 0 的列中,之后
Date
設(shè)置為索引。由于每個(gè)文件的列名稱都不同,因此最好使用
.iloc
對(duì)列進(jìn)行尋址。:
表示所有行,0
是數(shù)值數(shù)據(jù)的列索引。
df_dict.keys()
將返回所有鍵的列表使用 單獨(dú)訪問(wèn)數(shù)據(jù)框
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
添加回答
舉報(bào)