In many data manipulation tasks, extracting data from a Pandas DataFrame into a convenient format is necessary. One common need is to convert a DataFrame to a Python dictionary, where the elements of the first column become keys and the elements of other columns in the same row become values.
Consider the following DataFrame:
ID A B C 0 p 1 3 2 1 q 4 3 2 2 r 4 0 9
We want to convert this DataFrame to a dictionary of the following form:
{'p': [1,3,2], 'q': [4,3,2], 'r': [4,0,9]}
To achieve this, we can utilize the to_dict() method provided by Pandas. However, to align the DataFrame into the desired format, we need to set the 'ID' column as the index and transpose the DataFrame using .T. Additionally, we specify the orient argument in to_dict() to output a list of values for each column.
The following code demonstrates this approach:
df.set_index('ID').T.to_dict('list')
This will produce the desired dictionary:
{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}
Beyond the default dict format, Pandas offers a range of options for outputting dictionaries using the orient argument:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3