简体   繁体   English

使用 python pandas 将 JSON 文件转换为正确的格式

[英]Convert JSON file into proper format using python pandas

I want to convert JSON file into proper format.我想将 JSON 文件转换为正确的格式。 I have a JSON file as given below:我有一个 JSON 文件,如下所示:

{
    "fruit": "Apple",
    "size": "Large",
    "color": "Red",
    "details":"|seedless:true|,|condition:New|"

},
{
    "fruit": "Almond",
    "size": "small",
    "color": "brown",
    "details":"|Type:dry|,|seedless:true|,|condition:New|"

}

You can see the data in the details can vary.您可以在详细信息中看到数据可能会有所不同。

I want to change it into :我想把它改成:

{
    "fruit": "Apple",
    "size": "Large",
    "color": "Red",
    "seedless":"true",
    "condition":"New",

},
{
    "fruit": "Almond",
    "size": "small",
    "color": "brown",
    "Type":"dry",
    "seedless":"true",
    "condition":"New",

}

I have tried doing it in python using pandas as:我曾尝试使用 Pandas 在 python 中这样做:

import json
import pandas as pd
import re
df = pd.read_json("data.json",lines=True)

#I tried to change the pattern of data in details column as

re1 = re.compile('r/|(.?):(.?)|/')
re2 = re.compile('r\"(.*?)\":\"(.*?)\"')

df.replace({'details' :re1}, {'details' : re2},inplace = True, regex = True);

But that giving output as "objects" in all the rows of details column.但是,在详细信息列的所有行中都将输出作为“对象”。

Try this,尝试这个,

for d in data:
    details = d.pop('details')
    d.update(dict(x.split(":") for x in details.split("|") if ":" in x))

print(data)

[{'color': 'Red',
  'condition': 'New',
  'fruit': 'Apple',
  'seedless': 'true',
  'size': 'Large'},
 {'Type': 'dry',
  'color': 'brown',
  'condition': 'New',
  'fruit': 'Almond',
  'seedless': 'true',
  'size': 'small'}]

You can convert the (list of) dictionaries to a pandas data frame.您可以将(列表)字典转换为 Pandas 数据框。

import pandas as pd

# data is a list of dictionaries
data = [{
    "fruit": "Apple",
    "size": "Large",
    "color": "Red",
    "details":"|seedless:true|,|condition:New|"

},
{
    "fruit": "Almond",
    "size": "small",
    "color": "brown",
    "details":"|Type:dry,|seedless:true|,|condition:New|"

}]

# convert to data frame
df = pd.DataFrame(data)

# remove '|' from details and convert to list
df['details'] = df['details'].str.replace(r'\|', '').str.split(',')

# explode list => one row for each element
df = df.explode('details')

# split details into name/value pair
df[['name', 'value']] = df['details'].str.split(':').apply(lambda x: pd.Series(x))

# drop details column
df = df.drop(columns='details')

print(df)

    fruit   size  color       name value
0   Apple  Large    Red   seedless  true
0   Apple  Large    Red  condition   New
1  Almond  small  brown       Type   dry
1  Almond  small  brown   seedless  true
1  Almond  small  brown  condition   New

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

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