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]}
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()
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!