Home >Backend Development >Python Tutorial >How Can I Convert a Pandas DataFrame to a Dictionary with Specific Orientations?
Convert a Pandas DataFrame to a Dictionary
In Python, converting a Pandas DataFrame into a dictionary involves restructuring the data frame to align with the desired dictionary format. Specifically, the column names become dictionary keys, while the values in each row become the values associated with those keys.
To achieve this transformation, the to_dict() method proves valuable. This method accepts an 'orient' parameter that dictates the arrangement of the data. By default, it adopts the 'dict' orientation, where column names act as keys, and the values are dictionaries containing index-value pairs.
To produce a list of values for each column instead, as demonstrated in the sample output, the 'orient' parameter should be set to 'list':
df.set_index('ID').T.to_dict('list')
This line accomplishes several tasks:
The resulting dictionary takes the desired format, where the first column elements are keys, and the corresponding row elements are values.
While the 'list' orientation is suitable for the given scenario, other orient options exist, each producing a distinct dictionary format:
By understanding the different orientations, you can tailor the conversion to the desired dictionary structure.
The above is the detailed content of How Can I Convert a Pandas DataFrame to a Dictionary with Specific Orientations?. For more information, please follow other related articles on the PHP Chinese website!