简体   繁体   中英

How to remove delimeted pipe from my json column and split them to different columns and their respective values

"description": ID|100|\nName|Sam|\nCity|New York City|\nState|New York|\nContact|1234567890|\nEmail|1234@yahoo.com|

This is how my code in json looks like. I wanted to convert this json file to excel sheet to split the nested column to separate columns and have used pandas for it, but couldn't achieve it. The output I want in my excel sheet is:

ID Name City State Contact Email 100 Sam New York City New York 1234567890 1234@yahoo.com

I want to remove those pipes and the solution should be in pandas. Please help me out with this.

This could be one way:

import pandas as pd

j = {"description": "ID|100|\nName|Sam|\nCity|New York City|\nState|New York|\nContact|1234567890|\nEmail|1234@yahoo.com|"}

desc = j.get("description")
attributes = desc.split("\n")

df = pd.DataFrame()
d = {}

for attrib in attributes:
    (k, v, sp) = attrib.split("|")
    d[k] = v

df = df.append(d, ignore_index=True)
print(df)
df.to_csv("output.csv")

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