简体   繁体   中英

how to convert pipe delimited string into list python for column in pandas dataframe

I need to convert csv file to json. In csv file email is delimited by pipe(|) in a string. Need to convert into list. I am able to convert into list but only 1 email is coming in output.

Input Data in csf format

first_name, last_name, email
"ABC","DEF","abc@gmail.com|def@gmail.com"
"CBA","FED","cba@gmail.com|fed@gmail.com"

Expected Ouput Data in json format

[
    {
        "first_name" : "ABC",
        "last_name" : "DEF",
        "email" : ["abc@gmail","def@gmail"]
    }
    {
        "first_name" : "CBA",
        "last_name" : "DEF",
        "email" : ["abc@gmail","def@gmail"]
    }
]

Getting output

[
    {
        "first_name" : "ABC",
        "last_name" : "DEF",
        "email" : ["abc@gmail"]
    }
    {
        "first_name" : "CBA",
        "last_name" : "DEF",
        "email" : ["abc@gmail"]
    }
]

code tried

df = pd.read_csv("filename")
df.Email = df.Email.str.split('|')
df1 = df.to_json("filename", orient='records')

I am using pandas v1.0.5 and it works as expected.

在此处输入图像描述

In your example of csv data the first line has spaces after the comma, but that would just throw an error, when trying to access df.email .

Conclusion: The error must be somewhere else. Either you didn't share all relevant code with us, the data is actually different, or it actually does the job correctly and there is no error, but it's just how the data is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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