Home >Backend Development >Python Tutorial >How to Convert Pandas GroupBy Results into a Dictionary of Lists?

How to Convert Pandas GroupBy Results into a Dictionary of Lists?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 16:26:02344browse

How to Convert Pandas GroupBy Results into a Dictionary of Lists?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn