简体   繁体   中英

Pandas groupby + resample first is really slow - since version 0.22

I have a piece of code that groups a dataframe and runs resample('1D').first() for each group. Since I upgraded to 0.22.0, it runs much slower.

Setup code :

import pandas as pd
import numpy as np
import datetime as dt
import string


# set up some data
DATE_U = 50

STR_LEN = 10
STR_U = 50

N = 500

letters = list(string.ascii_lowercase)
def get_rand_string():
    return ''.join(np.random.choice(letters, size=STR_LEN))

dates = np.random.randint(0, 100000000, size=DATE_U)
strings = [get_rand_string() for _ in range(STR_U)]

df = pd.DataFrame({
    'date': np.random.choice(dates, N),
    'string': np.random.choice(strings, N),
})
df['date'] = pd.to_datetime(df['date'], unit='s')
df = df.set_index('date')

print('Shape: {}'.format(df.shape))
print(df.head())
print('\nUnique strings: {}'.format(df['string'].nunique()))
print('Unique dates: {}'.format(df.index.nunique()))

(Prints) :

Shape: (500, 1)
                       string
date                           
1973-02-07 19:57:43  wafadvlvty
1973-02-27 03:43:02  shofwwdhtu
1972-04-25 18:11:20  xwbbpwtsfj
1970-09-03 18:00:59  zkxwnqgrqp
1971-03-18 10:09:44  ofsaxqprdx

Unique strings: 50
Unique dates: 50

Testing the groupby + resample.first :

%%timeit -n 3 -r 3

def __apply(g):   
    g = g.resample('1D').first()
    return g

print('Pandas version: {}'.format(pd.__version__))

dfg = df.groupby('string').apply(__apply)

For Pandas 0.21.0:

Pandas version: 0.21.0
118 ms ± 1.63 ms per loop (mean ± std. dev. of 3 runs, 3 loops each)

For Pandas 0.22.0:

Pandas version: 0.22.0
3 loops, best of 3: 2.3 s per loop

Which is about 20 times slower. My questions is why is that? And is there a way to make this equally fast in 0.22.0?

使用 .head(1) 代替如下

g = g.resample('1D').head(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM