pandas.DataFrame.opti.to_paramdict#

DataFrame.opti.to_paramdict()[source]#

Cast a single-column DataFrame into a ParamDict1D/ParamDictND.

Note: The opti-extensions package has to be imported first to use this method with pandas.

Returns:
ParamDict1D or ParamDictND
  • A single-index, single-column DataFrame will be cast into a ParamDict1D having index label as keys and column values as values. The index name will be set as the ParamDict1D.key_name attribute (as str). The column name will be set as the ParamDict1D.value_name attribute (as str).

  • A multi-index, single-column DataFrame will be cast into a ParamDictND having tuple of index labels as keys and column values as values. The multi-index names will be set as the ParamDictND.key_names attribute (as list[str]). The column name will be set as the ParamDictND.value_name attribute (as str).

Raises:
ValueError

If the DataFrame is empty.

ValueError

If the DataFrame has multiple columns.

ValueError

If the DataFrame has duplicate index label(s).

TypeError

If the DataFrame has index label(s) that are not scalar (any iterable except string).

TypeError

If the DataFrame column values are not int or float.

See also

pandas.Series.opti.to_paramdict

Cast a Series into a ParamDict1D/ParamDictND.

Examples

>>> import pandas as pd
>>> import opti_extensions  # required to access this method

Casting a single-index, single-column DataFrame into a ParamDict1D

>>> inventory = pd.DataFrame({'PRODUCT': ['chair', 'desk'], 'UNITS': [200, 500]})
>>> inventory
  PRODUCT  UNITS
0   chair    200
1    desk    500
>>> inventory_units = inventory.set_index('PRODUCT')
>>> inventory_units
         UNITS
PRODUCT
chair      200
desk       500
>>> inventory_units.opti.to_paramdict()
ParamDict1D: PRODUCT -> UNITS
{'chair': 200, 'desk': 500}

Casting a multi-index, single-column DataFrame into a ParamDictND

>>> routes = pd.DataFrame(
...     {
...         'ORI': ['Delhi', 'Delhi', 'Seattle', 'Tokyo'],
...         'DES': ['Seattle', 'Tokyo', 'Tokyo', 'Delhi'],
...         'DIST': [11303, 5836, 7695, 5830],
...     }
... )
>>> routes
       ORI      DES   DIST
0    Delhi  Seattle  11303
1    Delhi    Tokyo   5836
2  Seattle    Tokyo   7695
3    Tokyo    Delhi   5830
>>> routes_dist = routes.set_index(['ORI', 'DES'])
>>> routes_dist
                  DIST
ORI     DES
Delhi   Seattle  11303
        Tokyo     5836
Seattle Tokyo     7695
Tokyo   Delhi     5830
>>> routes_dist.opti.to_paramdict()
ParamDictND: (ORI, DES) -> DIST
{('Delhi', 'Seattle'): 11303,
 ('Delhi', 'Tokyo'): 5836,
 ('Seattle', 'Tokyo'): 7695,
 ('Tokyo', 'Delhi'): 5830}