Home > OS >  Create a dictionary containing a dictionary with a series from a pandas dataframe
Create a dictionary containing a dictionary with a series from a pandas dataframe

Time:12-29

I have a dataframe (df) that looks like this:

Index Cell_1 Cell_2
Metal_1 0.2 0.1
Metal_2 0.4 0.2
Metal_3 0.3 0.3
Metal_4 0.5 0.7

I want to create a dictionary of dictionaries that houses a series.

My current code is this:

df_dict = df.to_dict('series')
print(df_dict)

it returns a dictionary as follows:

{'Cell_1': Metal_1 0.2
Metal_2 0.4
Metal_3 0.3
Metal_4 0.5
Name: Cell_1, dtype:flaot64, 'Cell_2': Metal_1 0.1
Metal_2 0.2
Metal_3 0.3
Metal_4 0.7
Name: Cell_2, dtype:flaot64}

Can I curate something to get a dictionary like this:

{'Cell_1': {'processed_result': Metal_1 0.2
Metal_2 0.4
Metal_3 0.3
Metal_4 0.5
dtype: float64}
Name: Cell_1, dtype:flaot64, 'Cell_2': {'processed_result': Metal_1 0.1
Metal_2 0.2
Metal_3 0.3
Metal_4 0.7
dtype: float64}
Name: Cell_2, dtype:flaot64}

see above. not applicable

CodePudding user response:

yes a dictionary comprehension helps here:

In [362]: {cell: {"processed_result": series}
           for cell, series in df.to_dict("series").items()}
Out[362]:
{'Cell_1': {'processed_result': Metal_1    0.2
  Metal_2    0.4
  Metal_3    0.3
  Metal_4    0.5
  Name: Cell_1, dtype: float64},
 'Cell_2': {'processed_result': Metal_1    0.1
  Metal_2    0.2
  Metal_3    0.3
  Metal_4    0.7
  Name: Cell_2, dtype: float64}}

In the "value" part of the comprehension, we put a 1-length, "processed_result"-keyed dictionary.

  • Related