如何加快熊猫drop()方法?

时间:2019-08-07 11:00:08

标签: python excel pandas numpy

我有一个大型的excel文件,可清理约200000行。因此,如果满足条件,我将使用熊猫删除不需要的行,但是运行需要一些时间。

我当前的代码如下

declare 
  type tr is record (id test.id%type, rwd urowid);
  type tt is table of tr;
  vt tt;
begin 
  select id, rwd 
    bulk collect into vt
    from (select rowid rwd, id, count(1) over (partition by id, amount, price, type) cnt,
                 row_number() over (partition by id, amount, price, type order by null) rn
           from test)
    where cnt > 1 and rn / cnt > .5;

  forall i in 1..vt.count
    update test set exclude_reason = 'Duplicate' 
      where id = vt(i).id and rowid = vt(i).rwd;

end;

此代码行大约需要30分钟才能完成。有没有更有效的方法来放熊猫行?如果不能,我可以使用numpy获得相同的输出吗?

我不太熟悉熊猫或numpy,所以如果您有任何分享的技巧将很有帮助。

编辑:

我使用phonenumbers lib检查电话号码是否有效。如果它不是有效的电话号码,那么我将该行放在该行上。

示例数据

def cleanNumbers(number):  # checks number if it is a valid number
    vaild = True
    try:
        num = pn.parse('+' + str(number), None)
        if not pn.is_valid_number(num):
            vaild = False
    except:
        vaild = False
    return vaild

for UncleanNum in tqdm(TeleNum):
    valid = cleanNumbers(UncleanNum)  # calling cleanNumbers function
    if valid is False:
        df = df.drop(df[df.telephone == UncleanNum].index)  
        # dropping row if number is not a valid number

输出

address     name    surname     telephone
Street St.  Bill    Billinson   7398673456897<--let say this is wrong
Street St.  Nick    Nick        324523452345
Street St.  Sam     Sammy       234523452345
Street St.  Bob     Bob         32452345234534<--and this too
Street St.  John    Greg        234523452345

这是我的代码所做的,但是很慢。

1 个答案:

答案 0 :(得分:1)

在我看来,这里的主靴口不是下降的,而是针对大量值重复自定义功能。

创建所有有效数字的列表,然后用boolean indexingSeries.isin进行过滤:

v = [UncleanNum for UncleanNum in tqdm(TeleNum) if cleanNumbers(UncleanNum)]

df = df[df.telephone.isin(v)]

编辑:

经过一些测试的解决方案应该简化,因为函数返回布尔值:

df1 = df[df['telephone'].apply(cleanNumbers)]