pandas使用apply()怎样知道出错在第几行数据?

在使用apply之后想知道错误发生在第几行,怎么办?
例如
df=pd.DataFrame(["1","2","3",4])
df.apply(lambda x:x+"a")
应该在df的第4行报错,但是怎样获得这个df的行数呢?
image.png

阅读 6.6k
2 个回答

一个思路是把转换操作(add)包装一下来获取额外的信息

class ops(object):  
    @staticmethod  
  def from_list(list):  
        return [ops(i,list[i]) for i in range(len(list))]  
  
    def __init__(self,index,val):  
        self.val = val  
        self.index = index  
        pass  
 def __add__(self, other):  
        try:  
            return self.val + other  
        except BaseException as ex:  
            print("add error index %d val " % self.index,self.val)  
            exit(-1)  
  
df=pd.DataFrame(ops.from_list(["1","2","3",4]))  
df.apply(lambda x:x+"a") #add error index 3 val  4

最后一个TypeError有箭头指出 ----> 第二行发生了问题
最后一个TypeError

try:
    df.apply(lambda x:x+"a")
except Exception as e:
    print("error x is ", x)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题