Skip to main content
 首页 » 编程设计

python之在 iPython 修剪输出中解释 {isinstance}

2025年05月04日9lautakyan007

我正在尝试分析几行 Pandas 代码,当我运行 %prun 时,我发现我的大部分时间都被 {isinstance} 占用了。这种情况似乎经常发生——任何人都可以提出这意味着什么,并且为了加分,建议一种避免它的方法吗?

这并不意味着特定于应用程序,但如果这很重要,这里是代码的精简版本:

def flagOtherGroup(df): 
 
    try:mostUsed0 = df[df.subGroupDummy == 0].siteid.iloc[0] 
    except: mostUsed0 = -1 
 
    try: mostUsed1 = df[df.subGroupDummy == 1].siteid.iloc[0] 
    except: mostUsed1 = -1 
 
    df['mostUsed'] = 0  
 
    df.loc[(df.subGroupDummy == 0) & (df.siteid == mostUsed1), 'mostUsed'] = 1 
    df.loc[(df.subGroupDummy == 1) & (df.siteid == mostUsed0), 'mostUsed'] = 1 
 
    return df[['mostUsed']] 
 
%prun -l15  temp = test.groupby('userCode').apply(flagOtherGroup) 

修剪的顶线:

   Ordered by: internal time 
   List reduced from 531 to 15 due to restriction <15> 
 
   ncalls  tottime  percall  cumtime  percall filename:lineno(function) 
   834472    1.908    0.000    2.280    0.000 {isinstance} 
497048/395400    1.192    0.000    1.572    0.000 {len} 
    32722    0.879    0.000    4.479    0.000 series.py:114(__init__) 
    34444    0.613    0.000    1.792    0.000 internals.py:3286(__init__) 
    25990    0.568    0.000    0.568    0.000 {method 'reduce' of 'numpy.ufunc' objects} 
82266/78821    0.549    0.000    0.744    0.000 {numpy.core.multiarray.array} 
    42201    0.544    0.000    1.195    0.000 internals.py:62(__init__) 
    42201    0.485    0.000    1.812    0.000 internals.py:2015(make_block) 
   166244    0.476    0.000    0.615    0.000 {getattr} 
     4310    0.455    0.000    1.121    0.000 internals.py:2217(_rebuild_blknos_and_blklocs) 
    12054    0.417    0.000    2.134    0.000 internals.py:2355(apply) 
     9474    0.385    0.000    1.284    0.000 common.py:727(take_nd) 

请您参考如下方法:

isinstance、len 和getattr 只是内置函数。对 isinstance() function 的调用数量巨大这里;不是调用本身耗时多,而是函数被使用了834472次。

大概是 pandas 代码使用了它。