Python 大熊猫lambda函数。。。更快的计算
我有以下Python 大熊猫lambda函数。。。更快的计算,python,pandas,Python,Pandas,我有以下dataframe的dates和code df = pd.DataFrame( {'date': list(pd.date_range(start='2018-01-01', end='2018-12-30')) * 364, 'code': np.random.permutation(list(np.arange(23001, 23001 + 8281)) * 16)} ).sort_values('date', ascending=True).reset_index
dataframe
的dates
和code
df = pd.DataFrame(
{'date': list(pd.date_range(start='2018-01-01', end='2018-12-30')) * 364,
'code': np.random.permutation(list(np.arange(23001, 23001 + 8281)) * 16)}
).sort_values('date', ascending=True).reset_index(drop=True)
我想要的是,对于在某个特定时间发生的每一个代码
,计算在同一日期之前发生的所有相同的代码
def nb_code_at_date(x):
condition = (df['date'] <= x['date'])
return (df.loc[condition, 'code'] == x['code']).sum()
您如何处理以增加等待时间?我发现的另一个解决方案是使用pandas.crosstab函数来计算预定义的数据帧,该数据帧可以随时使用并修复
temp = pd.crosstab(df['date'], df['code'])
def nb_code_at_date2(x):
condition = (temp.index <= x['date'])
return (temp.loc[condition, x['code']]).sum()
%%timeit
df.head(1000).apply(lambda x: nb_code_at_date2(x), axis=1)
>>750 ms ± 73.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
temp=pd.交叉表(df['date'],df['code']))
def nb_代码_日期2(x):
条件=(温度指数>750 ms±73.3 ms/循环(7次运行的平均值±标准偏差,每个循环1次)
可以使用和完成任务:
一个代码能在一天内发生一次以上吗?是的,它可以在特定的时间发生每一个事件,做所有的相同的代码的出现,在它之后,但是在同一天需要计数。我认为这里没有时间上的差异,但是只有日期上的差异。因此,日内差异是不相关的。
temp = pd.crosstab(df['date'], df['code'])
def nb_code_at_date2(x):
condition = (temp.index <= x['date'])
return (temp.loc[condition, x['code']]).sum()
%%timeit
df.head(1000).apply(lambda x: nb_code_at_date2(x), axis=1)
>>750 ms ± 73.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
output = df.join(df.groupby(["code"]).cumcount().add(1).to_frame())
output = output.groupby(["code", "date"]).transform("max")