Converting GroupBy Results to Dictionary of Lists
In order to extract and group data from an Excel sheet, it is common to utilize the groupby function of the pandas library. However, when the desired output is a dictionary where keys correspond to group values and values are lists of corresponding elements, the conventional approach may not suffice.
To achieve this specific requirement, one solution is to utilize the apply and to_dict functions. The apply function allows for the application of a function to each group, in this case, converting Column3 to a list. The to_dict function then converts the result into a dictionary. The following code demonstrates this approach:
<code class="python">import pandas as pd excel = pd.read_excel(r"e:\test_data.xlsx", sheetname='mySheet', parse_cols'A,C') result = excel.groupby('Column1')['Column3'].apply(list).to_dict()</code>
This code will generate the desired output:
{0: [1], 1: [2, 3, 5], 2: [1, 2], 3: [4, 5], 4: [1], 5: [1, 2, 3]}
Alternatively, a more compact solution is to use a dictionary comprehension:
<code class="python">result = {k: list(v) for k, v in excel.groupby('Column1')['Column3']}</code>
This approach also produces the same desired output, providing a concise and efficient implementation.
The above is the detailed content of How to Convert Pandas GroupBy Results into a Dictionary of Lists?. For more information, please follow other related articles on the PHP Chinese website!