Data Science/Python
[pandas] Create pandas dataframe from nested dict.
DS-9VM
2022. 4. 6. 00:55
728x90
You can simply convert your `dictData` to the DataFrame and then take transpose, to make columns into index and index into columns.
Sample code
import pandas as pd
dictData = {
'id1':{'A': 0.2, 'B':0.3, 'C':0.4},
'id2':{'A': 0.05, 'B':0.8, 'C':0.1},
'id3':{'A': 0.15, 'B':0.6, 'C':0.25}
}
df = pd.DataFrame.from_dict(dictData, orient="index")
# df = pd.DataFrame(dictData).T ( same resule )
df
df output
pandas.DataFrame.from_dict
classmethod DataFrame.from_dict(data, orient='columns', dtype=None, columns=None)
- Construct DataFrame from dict of array-like or dicts.
- Creates DataFrame object from dictionary by columns or by index allowing dtype specification.
Parameters :
- data: dict
- Of the form {field : array-like} or {field : dict}.
- orient: {‘columns’, ‘index’, ‘tight’}, default ‘columns’
- The “orientation” of the data. If the keys of the passed dict should be the columns of the resulting DataFrame, pass ‘columns’ (default). Otherwise if the keys should be rows, pass ‘index’. If ‘tight’, assume a dict with keys [‘index’, ‘columns’, ‘data’, ‘index_names’, ‘column_names’].
- New in version 1.4.0: ‘tight’ as an allowed value for the orient argument
- dtype: dtype, default None
- Data type to force, otherwise infer.
- columns: list, default None
- Column labels to use when orient='index'. Raises a ValueError if used with orient='columns' or orient='tight'.
Returns: DataFrame
728x90