Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 有没有比groupby transform更快的替代方案?_Python_Pandas - Fatal编程技术网

Python 有没有比groupby transform更快的替代方案?

Python 有没有比groupby transform更快的替代方案?,python,pandas,Python,Pandas,我刚刚将Pandas更新为0.13.1,但现在一行代码(在0.12.0下已经很慢)变得慢得令人无法忍受。我不知道是否有更快的替代方案 我使用数据帧。假设我有这样一个: import pandas as pd df = pd.DataFrame({'A': ['one', 'one', 'two', 'three', 'three', 'one'], 'B': range(6)}) print df A B 0 one 0 1 one 1 2 two 2

我刚刚将Pandas更新为0.13.1,但现在一行代码(在0.12.0下已经很慢)变得慢得令人无法忍受。我不知道是否有更快的替代方案

我使用数据帧。假设我有这样一个:

import pandas as pd
df = pd.DataFrame({'A': ['one', 'one', 'two', 'three', 'three', 'one'], 'B': range(6)})
print df

       A  B
0    one  0
1    one  1
2    two  2
3  three  3
4  three  4
5    one  5
我通过首先按“a”分组并在B中选择每组的最后一个值来创建第三列“C”:

df['C'] = df.groupby('A')['B'].transform(lambda x: x.iloc[-1])
print df

      A   B  C
0    one  0  5
1    one  1  5
2    two  2  2
3  three  3  4
4  three  4  4
5    one  5  5
问题是:熊猫版本0.13.1有没有更快的方法


谢谢

是的,这正在等待实施:

但你可以这样做:

生成数据/组:

In [31]: np.random.seed(0)

In [32]: N = 120000

In [33]: N_TRANSITIONS = 1400

In [35]: transition_points = np.random.permutation(np.arange(N))[:N_TRANSITIONS]

In [36]: transition_points.sort()

In [37]: transitions = np.zeros((N,), dtype=np.bool)

In [38]: transitions[transition_points] = True

In [39]: g = transitions.cumsum()

In [40]: df = pd.DataFrame({ "signal" : np.random.rand(N)})

In [41]: grp = df["signal"].groupby(g)
以下是实际的转换:

In [42]: result2 = grp.transform(lambda x: x.iloc[-1])

In [43]: result1 = pd.concat([ Series([r]*len(grp.groups[i])) for i, r in enumerate(grp.tail(1).values) ],ignore_index=True)

In [44]: result1.equals(result2)
Out[44]: True
时间安排

In [26]: %timeit pd.concat([ Series([r]*len(grp.groups[i])) for i, r in enumerate(grp.tail(1).values) ],ignore_index=True)
10 loops, best of 3: 123 ms per loop

In [27]: %timeit grp.transform(lambda x: x.iloc[-1])
1 loops, best of 3: 472 ms per loop

我本打算建议使用cumcount和tail(1),但您需要的是其他东西(这些东西会快得多)。当这是瓶颈时,你想做什么?实际上,它必须是一个bug,而不仅仅是缓慢。使用熊猫0.12.1,在我的旧笔记本电脑上大约需要一分钟的时间,总共60万行。现在熊猫0.13.1在30分钟后仍能运行…请用一个例子(可能是np.random.rand)发布这个,我们可以在github上测试(计时):谢谢Jeff指出这一点。分组似乎对小玩具示例有效,但变换(两者)都无效。我收到了严重的KeyError:0和另一条NotImplementedError:消息。