【发布时间】:2020-03-30 02:51:08
【问题描述】:
我使用的数据集是:https://www.kaggle.com/rohanrao/nifty50-stock-market-data
它包含自 2000 年至 2020 年所有 NIFTY50 公司的股票市场数据。
每个文件包含以下列:['Date', 'Symbol', 'Series', 'Prev Close', 'Open', 'High', 'Low', 'Last', 'Close', 'VWAP', 'Volume', 'Turnover', 'Trades', 'Deliverable Volume', '%Deliverble']
我需要将所有文件中的'Close' 列编译成一个数据帧。以日期作为索引,列名作为文件名,即
Date ADANIPORTS ASIANPAINTS AXISBANK .....
2000-01-01 0 1500 300
2000-02-02 1 1600 400
...
某些文件仅包含较晚日期(例如 01-01-2007)的数据,如果缺少 'Close' 的值,则应将其列为 0,即 0 直到数据可用的日期。
目前我正在使用此代码。
df=pd.DataFrame()
for filename in filenames:
file=dir+filename+'.csv'
data = pd.read_csv(file,usecols=lambda x: x in ['Date', 'Close'])
data.rename(columns = {'Close':filename}, inplace = True)
data.set_index('Date',inplace=True)
df.join(data, how='outer')
这会返回一个 (0,0) DataFrame->df
我试过了
#Initialising df with GRASIM.csv, and then using join for the other dataframes
file01 = dir + "GRASIM" + '.csv'
df=pd.read_csv(file01,usecols=lambda x: x in ['Date', 'Close'])
df.rename(columns = {'Close':"GRASIM"}, inplace = True)
df.set_index('Date',inplace = True)
for filename in filenames:
file=dir+filename+'.csv'
data = pd.read_csv(file,usecols=lambda x: x in ['Date', 'Close'])
data.rename(columns = {'Close':filename}, inplace = True)
data.set_index('Date',inplace=True)
df.join(data, how='outer')
但这会返回最初初始化的数据帧,即
GRASIM
Date
2000-01-03 438.30
2000-01-04 437.15
... ...
不添加其他列。
这似乎是什么问题?
【问题讨论】:
标签: python database pandas dataframe merge