Home > Backend Development > Python Tutorial > How to Group Data by Column and Convert it to a Dictionary of Lists in Python?

How to Group Data by Column and Convert it to a Dictionary of Lists in Python?

DDD
Release: 2024-10-29 13:46:29
Original
759 people have browsed it

How to Group Data by Column and Convert it to a Dictionary of Lists in Python?

GroupBy Results to Dictionary of Lists

You have an Excel spreadsheet with three columns, Column1, Column2, and Column3. You want to extract the data, group it by Column1, and create a dictionary of lists that looks like this:

{0: [1],
1: [2, 3, 5],
2: [1, 2],
3: [4, 5],
4: [1],
5: [1, 2, 3]}
Copy after login

To achieve this result, you can use the following code:

excel = pandas.read_excel(r"e:\test_data.xlsx", sheetname='mySheet', parse_cols="A,C")
grouped_data = excel.groupby("Column1")["Column3"].apply(list).to_dict()
Copy after login

The groupby function groups the data by Column1 and returns a groupby object. The apply method is then used to apply the list function to the Column3 data, creating a list of values for each group. Finally, the to_dict method is used to convert the grouped data into a dictionary of lists.

The resulting dictionary will have the format that you specified, with the keys being the values in Column1 and the values being lists of the corresponding values in Column3.

The above is the detailed content of How to Group Data by Column and Convert it to a Dictionary of Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template