Skip to main content
 首页 » 编程设计

python之bool 索引中列表理解的性能

2024年10月01日7tuyile006

我目前正在尝试了解有关 Pandas 的更多信息,并且正在查看 Boolean Indexing文档中的部分。

在给出的示例中,注意到对于 DataFrame

In[439]: df2 = pd.DataFrame({'a' : ['one', 'one', 'two', 'three', 'two', 'one', 'six'], 
                             'b' : ['x', 'y', 'y', 'x', 'y', 'x', 'x'], 
                             'c' : np.random.randn(7)}) 
 
In[440]: df2 
Out[440]:  
       a  b         c 
0    one  x -0.858441 
1    one  y  0.643366 
2    two  y -0.862198 
3  three  x -0.408981 
4    two  y  1.137740 
5    one  x  0.829057 
6    six  x -1.251656 

使用类似 Series 的 map 方法

In [441]: criterion = df2['a'].map(lambda x: x.startswith('t')) 
 
In [442]: df2[criterion] 
Out[442]:  
       a  b         c 
2    two  y  0.041290 
3  three  x  0.361719 
4    two  y -0.238075 

比等效的列表理解更快

In [443]: df2[[x.startswith('t') for x in df2['a']]] 
Out[443]:  
       a  b         c 
2    two  y  0.041290 
3  three  x  0.361719 
4    two  y -0.238075 

对于这种情况,我将使用文档中未提及的 df2[df2.a.str.startswith('t')],因此我想对这些方法进行基准测试。


小型系列基准测试

%timeit df2[df2.a.str.startswith('t')] 
1000 loops, best of 3: 880 µs per loop 
 
%timeit df2[df2['a'].map(lambda x: x.startswith('t'))] 
1000 loops, best of 3: 783 µs per loop 
 
%timeit df2[[x.startswith('t') for x in df2['a']]] 
1000 loops, best of 3: 572 µs per loop 

令人惊讶的是,列表理解方法似乎是最快的!因此,我尝试使 DataFrame 大得多 并再次进行基准测试。

In[444]: df2 = pd.DataFrame({'a' : ['one', 'one', 'two', 'three', 'two', 'one', 'six']*1000000, 
                             'b' : ['x', 'y', 'y', 'x', 'y', 'x', 'x']*1000000, 
                             'c' : np.random.randn(7*1000000)}) 

大系列基准

%timeit df2[df2.a.str.startswith('t')] 
1 loop, best of 3: 5.89 s per loop 
 
%timeit df2[df2['a'].map(lambda x: x.startswith('t'))] 
1 loop, best of 3: 5.73 s per loop 
 
%timeit df2[[x.startswith('t') for x in df2['a']]] 
1 loop, best of 3: 3.95 s per loop 

列表理解似乎仍然是最快的,并且对于大型 Series,差异更加明显。


问题

Series 的 map 方法实际上通常比 bool 索引的列表理解更快吗?为什么列表理解方法在这里似乎实际上更快并且与 documentation section 相矛盾?

我的基准测试方法或测试很可能存在错误,而且我很清楚对于更复杂的标准(甚至是简单的标准),前两种方法中的一种比好得多更好查看并实现,但我这里的问题只是关于性能。

注意:我使用的是 Pandas 版本 0.18.1

请您参考如下方法:

IMO 这与 bool 索引无关 - 它与字符串系列有关:

In [204]: %timeit df.a.str.startswith('t') 
10 loops, best of 3: 75.7 ms per loop 
 
In [205]: %timeit df['a'].map(lambda x: x.startswith('t')) 
10 loops, best of 3: 76.5 ms per loop 
 
In [206]: %timeit [x.startswith('t') for x in df['a']] 
10 loops, best of 3: 39.7 ms per loop 
 
In [209]: %timeit [df.a.str[0] == 't'] 
10 loops, best of 3: 85.2 ms per loop 

DF 形状:70.000 x 3

In [207]: df.shape 
Out[207]: (70000, 3) 

在处理 string 系列时,列表理解通常会更快。

PS 我在这个例子中使用的是 Pandas 版本 0.19.2