How to group rows from a pandas DataFrame into lists by column value in Python

Grouping rows from a pandas DataFrame into lists by column value involves creating a new DataFrame with the same column headers as the original DataFrame. A certain column is chosen as the grouping column, which contains the unique values of that column in the original DataFrame. For each row in the new DataFrame, every column other than the the grouping column contains a list of the values for that column in the original DataFrame where the value of the grouping column in the original DataFrame matches the value of the grouping column in the new DataFrame.

Solution for How to group rows from a pandas DataFrame into lists by column value in Python : You can use pandas.core.groupby.PanelGroupBy.apply() to group rows into lists by column value Call pandas.DataFrame.groupby(group_column) to group the rows of the DataFrame by their group_column value. Then, with the result of this function as grouped_DataFrame, call pandas.core.groupby.PanelGroupBy.apply(function) using the syntax grouped_DataFrame[column].apply(list) to place the column value of each row into a list for that specific group. To reformat the DataFrame‘s indices to match the new DataFrame, call pandas.Series.reset_index().


how-to-group-rows-from-a-pandas-dataframe-into-lists-by-column-value-in-python