1

I have the panda dataframe df below;

        File       Hour
Name1   F1         1
Name2   F1         2

I want to convert it into json that looks like this;

{
    "Name1": {
        "File": "F1",
        "Hour": "1"
    },
    "Name2": {
        "File": "F2",
        "Hour": "2"
    }
}

How can I use df.to_json() to do this? I am welcomed to using other methods.

I am using python v3.9

mozway
  • 194,879
  • 13
  • 39
  • 75
FDL
  • 115
  • 8
  • `df.T.to_json()` or `df.to_json(orient='index')` – mozway Feb 17 '22 at 08:26
  • I would like to answer my own question, thanks to mozway comment. How do I do that now that the question is closed? – FDL Feb 17 '22 at 08:30
  • You don't need to, the question already has an answer in the duplicate ;) – mozway Feb 17 '22 at 08:32
  • @mozway, that question is not as helpful as your straightforward comment. That question has several answers which confuses a newbie like me. Stackoverflow experts cannot assume people like me is as smart as them. – FDL Feb 17 '22 at 08:34

1 Answers1

1

As hinted here, you can use to_json this way:

df.to_json(orient='index')

or

df.T.to_json()

output:

'{"Name1":{"File":"F1","Hour":1},"Name2":{"File":"F1","Hour":2}}'
mozway
  • 194,879
  • 13
  • 39
  • 75