2

I am trying to generate a text file with the following format:

{"0": ["n01440764", "tench"], "1": ["n01443537", "goldfish"], "2": ["n01484850", "great_white_shark"]}

I have input data in a DataFrame:

data = [('n02124075', 'egyptian_cat'),
 ('n04067472', 'reel'),
 ('n04540053', 'volleyball')]
df = pd.DataFrame(data)
df.head(n=2)

    0   1
0   n02124075   egyptian_cat
1   n04067472   reel

I have tried:

df.to_json(PATH/'my_file.json', orient='index')

json_f = json.dumps(df.to_dict(orient='list'))
with open(PATH/'my_file.json', 'w') as outfile:
    json.dump(json_tiny, outfile)

and various variations of these but cant work out how to generate output file with correct format. Ant ideas?

1 Answer 1

4

You'll need a specific orient called "list" that to_json does not offer, but to_dict does.

import json

with open('my_file.json', 'w') as f:
    json.dump(df.T.to_dict(orient='list'), f)

my_file.json

{
    "0": ["n02124075", "egyptian_cat"],
    "1": ["n04067472", "reel"],
    "2": ["n04540053", "volleyball"]
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.