我有一段代码可以对数据帧进行分组,并为每个组运行resample('1D').first()
。由于我升级到0.22.0,它运行得慢得多。
设置代码:
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()))
(打印):
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
测试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)
对于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)
对于Pandas 0.22.0:
Pandas version: 0.22.0
3 loops, best of 3: 2.3 s per loop
这大约慢20倍。我的问题是为什么?有没有办法在0.22.0中同样快速地实现这一目标?
答案 0 :(得分:0)
使用.head(1)代替
g = g.resample('1D').head(1)