我正在将一个非常大(1500 万行)的 csv 文件读入 Pandas 数据框。然后我想把它分成更小的(最终创建更小的 csv 文件,或者一个 Pandas 面板......)。 我有工作代码,但速度很慢。我相信它没有利用我的数据框是“有序的”这一事实。
df 看起来像:
ticker date open high low
0 AAPL 1999-11-18 45.50 50.0000 40.0000
1 AAPL 1999-11-19 42.94 43.0000 39.8100
2 AAPL 1999-11-22 41.31 44.0000 40.0600
...
1000 MSFT 1999-11-18 45.50 50.0000 40.0000
1001 MSFT 1999-11-19 42.94 43.0000 39.8100
1002 MSFT 1999-11-22 41.31 44.0000 40.0600
...
7663 IBM 1999-11-18 45.50 50.0000 40.0000
7664 IBM 1999-11-19 42.94 43.0000 39.8100
7665 IBM 1999-11-22 41.31 44.0000 40.0600
我想获取符号=='AAPL'的所有行,并用它制作一个数据框。然后是 symbol=='MSFT' 的所有行,依此类推。每个符号的行数不同,代码必须进行调整。我可能会加载一个新的“大”csv,其中一切都不同。
这是我想出的:
#Read database
alldata = pd.read_csv('./alldata.csv')
#get a list of all unique ticker present in the database
alltickers = alldata.iloc[:,0].unique();
#write data of each ticker in its own csv file
for ticker in alltickers:
print('Creating csv for '+ticker)
#get data for current ticker
tickerdata = alldata.loc[alldata['ticker'] == ticker]
#remove column with ticker symbol (will be the file name) and reindex as
#we're grabbing from somwhere in a large dataframe
tickerdata = tickerdata.iloc[:,1:13].reset_index(drop=True)
#write csv
tickerdata.to_csv('./split/'+ticker+'.csv')
这需要很长时间才能运行。我以为是文件 I/O,但我在 for 循环中注释了 write csv 部分,我发现这一行是问题所在:
tickerdata = alldata.loc[alldata['ticker'] == ticker]
我想知道 pandas 是否每次都在查看整个数据框。我知道数据框是按代码顺序排列的。有没有办法利用它?
非常感谢! 戴夫
请您参考如下方法:
最简单的方法是使用字典理解和 pandas groupby
dodf = {ticker: sub_df for ticker, sub_df in alldata.groupby('ticker')}
dodf['IBM']
ticker date open high low
7663 IBM 1999-11-18 45.50 50.0 40.00
7664 IBM 1999-11-19 42.94 43.0 39.81
7665 IBM 1999-11-22 41.31 44.0 40.06
