Creating nested json from dataframe in pandas for chatbot data (Intents, tag, pattern, responses)

Viewed 21

I am trying to generate a nested JSON from a DataFrame, where attributes are distributed in several rows. Dataframe which I have

This is the format I want. [![what I need][2]][2]

{ "intents" : [ "tag": "Glacier cave", "patterns": ["how are glacier caves formed", "what is glacier cave?", 'give me info on glacier caves',"where is glacier cave formed?"] "responses": ["A partly submerged glacier cave on Perito Moreno Glacier","The ice facade is approximately 60 m high", "A glacier cave is a cave formed within the ice of a glacier", "Glacier caves are often called ice caves , but this term is properly used to describe bedrock caves that contain year-round ice"] ] }

1 Answers

You can groupby and agg columns to lists, then convert to dictionary.

df = df.groupby(["tag"]).agg({"pattern": pd.Series.to_list, "response": pd.Series.to_list}).reset_index()
df_dict = {"intents": {"tag": df.set_index("tag").transpose().to_dict()}}
Related