Skip to main content
 首页 » 编程设计

python之由于函数中的 "%"语法,Jupyter 中的 %timeit 问题

2025年02月15日8虾米哥

我想在 Jupyter 中%timeit 一个函数。

生成数据

df["One"] = range(1,1001) 
df["Two"] = range(2000, 3000) 
df["Three"] = range(3000, 4000) 
df.set_index(["One"], drop = True, inplace = True) 

设置函数

def test_iterrows(df): 
    for index, row in df.iterrows(): 
        if (row["Three"] & 1 == 0):   
            df.loc[index, "Three"] = "Even" 
        else: 
            df.loc[index, "Three"] = "Odd" 
    print df.head() 
    gc.collect() 
return None 

当我运行 test_iterrows(df) 时,我得到:

      Two Three 
One             
1    2000  Even 
2    2001   Odd 
3    2002  Even 
4    2003   Odd 
5    2004  Even 

很好。该功能有效。但是,当我执行 %timeit test_iterrows(df) 时,出现错误:

<ipython-input-29-326f4a0f49ee> in test_iterrows(df) 
     13 def test_iterrows(df): 
     14     for index, row in df.iterrows(): 
---> 15         if (row["Three"] & 1 == 0): 
     16             df.loc[index, "Three"] = "Even" 
     17         else: 
 
TypeError: unsupported operand type(s) for &: 'str' and 'int' 

这是怎么回事?我的(可能是错误的)解释是,我显然不能使用包含 % 的 %timeit 函数。

这是怎么回事?

请您参考如下方法:

%timeit 重复执行语句,函数就地更改 df。请注意,当我只调用该函数两次时,我得到了相同的异常:

test_iterrows(df) 
test_iterrows(df) 
# TypeError: unsupported operand type(s) for &: 'str' and 'int' 

你可能应该传入一个copy,尽管这会稍微“偏离”时间,因为它也会计算复制它所花费的时间:

%timeit test_iterrows(df.copy())  # time the execution with a copy 
%timeit df.copy()                 # compared to the time it takes to just copy it 

另外,我不太确定 gc.collect() 调用应该在那里做什么,因为 gc.collect 只是垃圾收集不能收集的对象由于引用循环而被正常方式丢弃。