简体   繁体   English

如何在 json.loads Panda Dataframe 期间转换错误时打印索引(行号)

[英]How to print index (Row number) while conversion error during json.loads Panda Dataframe

I am using below code for Json load which works fine for valid json string, but for non valid it throws error.我正在使用下面的代码进行 Json 负载,它适用于有效的 json 字符串,但对于无效它会引发错误。

orgdf['data'].apply(json.loads)

在此处输入图像描述

I just need to know for which index (row number) there is an invalid record for which Jason.loads giving error.我只需要知道 Jason.loads 给出错误的无效记录对于哪个索引(行号)。

I know I can do it using dataframe enumeration (for loop), but looking for an efficient way to do that as it contains Million records.我知道我可以使用 dataframe 枚举(for循环)来做到这一点,但正在寻找一种有效的方法来做到这一点,因为它包含百万条记录。

It will be great if someone can help on the same.如果有人可以提供同样的帮助,那就太好了。

You can create a custom function where you wrap the json.loads call in a try/except and then call this function inside apply .您可以创建一个自定义 function 在其中将json.loads调用包装在 try/except 中,然后在apply中调用此 function。 See also this answer .另请参阅此答案

def is_valid_json(s):
    try:
        json.loads(s)
    except (json.JSONDecodeError, ValueError):
        return False
    return True

# Mark valid JSON strings
valid = orgdf['data'].apply(is_valid_json)

# Extract indices with _invalid_ strings
invalid_indices = valid[~valid].index

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM