Pandas 将一列按另一列分组

use*_*808 2 python group-by dataframe pandas

我有一个 pandas 数据框,如下所示:

A B
1 a
1 b
1 c
2 d
2 e
2 f
Run Code Online (Sandbox Code Playgroud)

我想通过“A”列获取“B”列的值列表,因此最终产品如下所示:

list_one = [a, b, c]
list_two = [d, e, f]
Run Code Online (Sandbox Code Playgroud)

我试过了:

df.groupby(['A','B'])
Run Code Online (Sandbox Code Playgroud)

但是,这并没有达到我想要的效果。

实现这一目标的优雅 Python 方式是什么?

ch3*_*hau 5

import pandas as pd

df = pd.DataFrame([
    {'A':1, 'B': 'a'},
    {'A':1, 'B': 'b'},
    {'A':1, 'B': 'c'},
    {'A':2, 'B': 'd'},
    {'A':2, 'B': 'e'},
    {'A':2, 'B': 'f'}])

list(df.groupby('A')['B'].apply(list).values)

# Output
# [['a', 'b', 'c'], ['d', 'e', 'f']]
Run Code Online (Sandbox Code Playgroud)