Convert pandas data frame to JSON with strings separated

DavidLindhagen

I have a pandas.dataframe named 'df' with the following format:

group_name Positive_Sentiment Negative_Sentiment
group1 helpful, great support slow customer service, weak interface, bad management

I would like to convert this dataframe to a JSON file with the following format:

[{
"Group Name": "group1",
"Postive Sentiment": [
"helpful",
"great support"
],
"Negative Sentiment": [
"slow customer service",
"weak interface",
"bad management"
]
}
]

So far I have used this:

    import json
    b = []
    for i in range(len(df)):
        x={}
        x['Group Name']=df.iloc[i]['group_name']
        x['Positive Sentiment']= [df.iloc[i]['Positive_Sentiment']]
        x['Negative Sentiment']= [df.iloc[i]['Negative_Sentiment']]
        b.append(x)
    
    ##Export
    with open('AnalysisResults.json', 'w') as f:
        json.dump(b, f, indent = 2)

This results in:

[{
"Group Name": "group1",
"Postive Sentiment": [
"helpful,
great support"
],
"Negative Sentiment": [
"slow customer service,
weak interface,
bad UX"
]
}
]

You can see it is quite close. The crucial difference is the double-quotes around the ENTIRE contents of each row (e.g., "helpful, great support") instead of each comma-separated string in the row (e.g., "helpful", "great support"). I would like double-quotes around each string.

Tranbi

You can apply split(",") to your columns:


from io import StringIO
import pandas as pd
import json

inp = StringIO("""group_name    Positive_Sentiment  Negative_Sentiment
group1  helpful, great support  slow customer service, weak interface, bad management
group2  great, good support     interface meeeh, bad management""")

df = pd.read_csv(inp, sep="\s{2,}")

def split_and_strip(sentiment):
         [x.strip() for x in sentiment.split(",")]

df["Positive_Sentiment"] = df["Positive_Sentiment"].apply(split_and_strip)
df["Negative_Sentiment"] = df["Negative_Sentiment"].apply(split_and_strip)

print(json.dumps(df.to_dict(orient="record"), indent=4))

# to save directly to a file:
with open("your_file.json", "w+") as f:
    json.dump(df.to_dict(orient="record"), f, indent=4)

Output:

[
    {
        "group_name": "group1",
        "Positive_Sentiment": [
            "helpful",
            "great support"
        ],
        "Negative_Sentiment": [
            "slow customer service",
            "weak interface",
            "bad management"
        ]
    },
    {
        "group_name": "group2",
        "Positive_Sentiment": [
            "great",
            "good support"
        ],
        "Negative_Sentiment": [
            "interface meeeh",
            "bad management"
        ]
    }
]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Convert pandas data frame to series

Convert list into a pandas data frame

Convert comma-separated keywords into columns in a data frame

How to convert a list of strings to data frame?

Convert nested json to pandas data frame

Issues with try/except, attempting to convert strings to integers in pandas data frame where possible

Convert json list to data frame

Convert data frame to json in R

[Pandas, Python]; Retain Empty Columns in Space Separated Data Frame

split strings and convert to data frame

Convert list of multiple strings into a Python data frame

Pandas data frame: Getting tuples groups separated by 'NaN' in a column

Convert JSON data in data frame Python

How to convert a pandas data frame to nested json

How to convert pipe separated data into JSON?

Convert a pandas data frame to a pandas data frame with another style

Pandas data frame: plotting average for comma separated strings

How to convert XML data as a pandas data frame?

How to convert the data separated by ',' into the next row? (Pandas)

in python how do i convert a list of strings to pandas data frame

How to convert nested comma separated column inside a pandas data frame to specific format in Python

Convert dictionary to pandas data frame

How to find the number of unique values in comma separated strings stored in an pandas data frame column?

convert pandas data frame column values into comma separated strings

Concatenating Strings and Items from a Pandas Data Frame

Filtering pandas data frame based on different entries in a column (list of comma-separated strings)

replacing strings within a pandas data frame column

Nested JSON to Pandas Data frame

Convert Exchange Rate API JSON TO Pandas Data Frame