如果事先知道条目的数量,就应该预先分配空间,同时提供索引(以不同答案中的数据为例):import pandas as pdimport numpy as np# we know we're gonna have 5 rows of datanumberOfRows = 5# create dataframedf = pd.DataFrame(index=np.arange(0, numberOfRows), columns=('lib', 'qty1', 'qty2') )# now fill it up row by rowfor x in np.arange(0, numberOfRows):
#loc or iloc both work here since the index is natural numbers
df.loc[x] = [np.random.randint(-1,1) for n in range(3)]In[23]: dfOut[23]:
lib qty1 qty20 -1 -1 -11 0 0 02 -1 0 -13 0 -1 04 -1 0 0速度比较In[30]: %timeit tryThis() # function wrapper for this answerIn[31]: %timeit tryOther() # function wrapper without index (see, for example, @fred)1000 loops, best of 3: 1.23 ms per loop100 loops, best of 3: 2.31 ms per loop而且-从注释中-6000的大小,速度差变得更大了:增加数组(12)的大小和行数(500)使速度差异更显着:313 ms vs 2.29s