【问题标题】:Getting IndexingError while using custom function with apply in python在python中使用带有apply的自定义函数时出现IndexingError
【发布时间】:2019-08-12 07:54:38
【问题描述】:

我需要根据我的数据验证电话号码是否有效。 我在 python 中使用 phonenumbers 库

我创建了一个可以工作的 for 循环,但它太慢了,所以我尝试在 apply 函数中使用相同的 for 循环,但出现索引错误


    for i in range(len(df)):

        num = df.loc[i,'Primary Phone #']
        region = df.loc[i,'Override Address Country']
        try:
            output = phonenumbers.parse(num, region=region)
        except phonenumbers.NumberParseException:
            df.loc[i,'validation'] = False
        else:
            df.loc[i,'validation'] = phonenumbers.is_valid_number(output)

temp_data.apply(number_validation, axis = 0/1)

IndexingError: ('Too many indexers', 'occured at index Work Order Code')

【问题讨论】:

    标签: python-3.x pandas apply


    【解决方案1】:

    我可能会使用apply,就像您尝试过的那样,但请确保提供参数:

    def verify_number(x):
        return phonenumbers.parse(
            x['Primary Phone #'],
            region=x['Override Address Country']
        )
    
    df.apply(verify_number, axis=1)
    

    如果这仍然太慢,您可以考虑使用CythonNumbapandas.eval() 来提高性能,如pandas user guide 中所述。

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 2021-10-08
      • 2020-02-12
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 2017-07-09
      • 1970-01-01
      相关资源
      最近更新 更多