Parsing a JSON string which was loaded from a CSV using Pandas

后端 未结 5 1055
野的像风
野的像风 2020-11-27 03:24

I am working with CSV files where several of the columns have a simple json object (several key value pairs) while other columns are normal. Here is an example:



        
5条回答
  •  借酒劲吻你
    2020-11-27 04:25

    Option 1

    If you dumped the column with json.dumps before you wrote it to csv, you can read it back in with:

    import json
    import pandas as pd
    
    df = pd.read_csv('data/file.csv', converters={'json_column_name': json.loads})
    

    Option 2

    If you didn't then you might need to use this:

    import json
    import pandas as pd
    
    df = pd.read_csv('data/file.csv', converters={'json_column_name': eval})
    

    Option 3

    For more complicated situations you can write a custom converter like this:

    import json
    import pandas as pd
    
    def parse_column(data):
        try:
            return json.loads(data)
        except Exception as e:
            print(e)
            return None
    
    
    df = pd.read_csv('data/file.csv', converters={'json_column_name': parse_column})
    

提交回复
热议问题