Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas quantile function very slow

I want to calculate quantiles/percentiles on a Pandas Dataframe. However, the function is extremely slow. I repeated it with Numpy and I found that calculating it in Pandas takes almost 10 000 times longer!

Does anybody know why this is the case? Should I rather calculate it using Numpy and then create a new DataFrame instead of using Pandas?

See my code below:

import time
import pandas as pd
import numpy as np

q = np.array([0.1,0.4,0.6,0.9])
data = np.random.randn(10000, 4)
df = pd.DataFrame(data, columns=['a', 'b', 'c', 'd'])
time1 = time.time()
pandas_quantiles = df.quantile(q, axis=1)
time2 = time.time()
print 'Pandas took %0.3f ms' % ((time2-time1)*1000.0)

time1 = time.time()
numpy_quantiles = np.percentile(data, q*100, axis=1)
time2 = time.time()
print 'Numpy took %0.3f ms' % ((time2-time1)*1000.0)

print (pandas_quantiles.values == numpy_quantiles).all()
# Output:
# Pandas took 15337.531 ms
# Numpy took 1.653 ms
# True
like image 267
Kritz Avatar asked Nov 16 '15 20:11

Kritz


1 Answers

This issue is solved for recent versions of Pandas with python 3. Pandas is less than two times longer on small arrays, and I get a 5% difference on larger arrays.

I get the following output with pandas 0.24.1 and Python 3:

import time
import pandas as pd
import numpy as np

q = np.array([0.1,0.4,0.6,0.9])
data = np.random.randn(10000, 4)
df = pd.DataFrame(data, columns=['a', 'b', 'c', 'd'])
time1 = time.time()
pandas_quantiles = df.quantile(q, axis=1)
time2 = time.time()
print 'Pandas took %0.3f ms' % ((time2-time1)*1000.0)

time1 = time.time()
numpy_quantiles = np.percentile(data, q*100, axis=1)
time2 = time.time()
print 'Numpy took %0.3f ms' % ((time2-time1)*1000.0)

print (pandas_quantiles.values == numpy_quantiles).all()
# Output:
# Pandas took 3.415 ms
# Numpy took 2.040 ms
# True
like image 148
Adrien Pacifico Avatar answered Oct 29 '22 16:10

Adrien Pacifico