Home > OS >  How to pass a JSON or DICT into a dataframe with pandas?
How to pass a JSON or DICT into a dataframe with pandas?

Time:10-28

I have this JSON/DICT in Python and I need to pass it to a datframe:

{
    "filters": [
        {
            "field": "example1",
            "operation": "like",
            "values": [
                "Completed"
            ]
        },
        {
            "field": "example2",
            "operation": "like",
            "values": [
                "value1",
                "value2",
                "value3",
            ]
        }
    ]
}

DF that i need:

example1 example2
Completed ["value1","value2","value3"]

CodePudding user response:

Try:

dct = {
    "filters": [
        {"field": "example1", "operation": "like", "values": ["Completed"]},
        {
            "field": "example2",
            "operation": "like",
            "values": [
                "value1",
                "value2",
                "value3",
            ],
        },
    ]
}

df = pd.DataFrame(
    [
        {
            f["field"]: f["values"][0] if len(f["values"]) == 1 else f["values"]
            for f in dct["filters"]
        }
    ]
)
print(df)

Prints:

    example1                  example2
0  Completed  [value1, value2, value3]

CodePudding user response:

alternative:

import pandas as pd
dictt = {
    "filters": [
        {"field": "example1", "operation": "like", "values": ["Completed"]},
        {
            "field": "example2",
            "operation": "like",
            "values": [
                "value1",
                "value2",
                "value3",
            ],
        },
    ]
}
df=pd.DataFrame(dictt)
df=df['filters'].apply(pd.Series).drop('operation',axis=1).set_index('field').T.explode('example1')
print(df)
'''
        example1    example2
values  Completed   ['value1', 'value2', 'value3']

'''
  • Related