Recently, I often use pandas to do some data analysis, I feel that the function is indeed very powerful, and it is more convenient to get started. But no opinion found a performance problem about the assignment of
DataFrame and Series.
Extract some data from the Internet and put them into the DataFrame one by one. When the amount of data is large, it feels very slow. It was originally thought that it was time-consuming for DataFrame operation, but it would be much faster to read the data with a two-dimensional list array and then put it into the DataFrame at once. Write a simple test program for comparison.
1 """
2 Created on Sun Jul 12 16:29:57 2015
3 @author: hbhuyt
4 """
5
6 import pandas as pd
7 import random
8 import timeit
9
10
11 def func1():
12 aa = []
13 for x in xrange(200):
14 aa.append([random.randint(0, 1000) for r in xrange(5)])
15 pdaa = pd.DataFrame(aa)
16
17 def func2():
18 pdbb = pd.DataFrame()
19 for y in xrange(200):
20 pdbb[y] = pd.Series([random.randint(0, 1000) for r in xrange(5)])
twenty one
22 def func3():
23 aa = {}
24 for x in xrange(200):
25 aa[str(x)] = random.randint(0, 1000)
26 psaa = pd.Series(aa)
27
28 def func4():
29 psbb = pd.Series()
30 for y in xrange(200):
31 psbb[str(y)] = random.randint(0, 1000)
32
33
34 t1 = timeit.timeit(stmt =func1, number=1000)
35 t2 = timeit.timeit(stmt =func2, number=1000)
36 print t1, t2
37 t3 = timeit.timeit(stmt =func3, number=1000)
38 t4 = timeit.timeit(stmt =func4, number=1000)
39 print t3, t4
40
The test results are as follows:
It can be seen that filling data in a row by row in a DataFrame is very time-consuming (not related to the number of columns in the added row). It is best to fill the data in a standard container such as list or dict and import it into the DataFrame at once.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.