0

I need to convert Pandas Series to a Dictionary, without Index (like pandas.DataFrame.to_dict('r')) - code is below:

grouped_df = df.groupby(index_column)
for key, val in tqdm(grouped):
    json_dict[key] = val.apply(lambda x: x.to_dict(), axis=1).to_dict()

Currently, I get output like so:

{
   "15717":{
      "col1":1.61,
      "col2":1.53,
      "col3":1.0
   },
   "15718":{
      "col1":10.97,
      "col2":5.79,
      "col3":2.0
   },
   "15719":{
      "col1":15.38,
      "col2":12.81,
      "col3":1.0
   }
}

but i need output like:

[
   {
      "col1":1.61,
      "col2":1.53,
      "col3":1.0
   },
   {
      "col1":10.97,
      "col2":5.79,
      "col3":2.0
   },
   {
      "col1":15.38,
      "col2":12.81,
      "col3":1.0
   }
]

Thanks for your help!

Edit: Here is the original dataframe:

        col1   col2 col3
2751    5.46    1.0 1.11
2752    16.47   0.0 6.54
2753    26.51   0.0 18.25
2754    31.04   1.0 28.95
2755    36.45   0.0 32.91
Ramsha Siddiqui
  • 460
  • 6
  • 20

2 Answers2

2

Two ways of doing that:

[v for _, v in df.to_dict(orient="index").items()]

Another one:

df.to_dict(orient="records")

The output, either way, is:

[{'col1': 1.61, 'col2': 1.53, 'col3': 1.0},
 {'col1': 10.97, 'col2': 5.79, 'col3': 2.0},
 {'col1': 15.38, 'col2': 12.81, 'col3': 1.0}]
Roy2012
  • 11,755
  • 2
  • 22
  • 35
1

You can try:

df.T.to_dict('r')

Output:

[{'col1': 1.61, 'col2': 1.53, 'col3': 1.0},
 {'col1': 10.97, 'col2': 5.79, 'col3': 2.0},
 {'col1': 15.38, 'col2': 12.81, 'col3': 1.0}]
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74