在 Pandas groupby 结果中包含索引

zyx*_*xyz 7 python pandas pandas-groupby

有了 Pandas groupby,我可以做这样的事情:

>>> df = pd.DataFrame(
...     {
...         "A": ["foo", "bar", "bar", "foo", "bar"],
...         "B": ["one", "two", "three", "four", "five"],
...     }
... )
>>> print(df)
     A      B
0  foo    one
1  bar    two
2  bar  three
3  foo   four
4  bar   five
>>> print(df.groupby('A')['B'].unique())
A
bar    [two, three, five]
foo           [one, four]
Name: B, dtype: object
Run Code Online (Sandbox Code Playgroud)

我正在寻找的是生成索引列表而不是 B 列列表的输出:

A
bar    [1, 2, 4]
foo    [0, 3]
Run Code Online (Sandbox Code Playgroud)

但是,groupby('A').index.unique() 不起作用。什么语法可以为我提供我想要的输出?尽管我确实需要在实际应用程序中按两列进行分组,但我非常乐意以除 groupby 之外的其他方式来执行此操作。

moz*_*way 4

您不一定需要在 中有标签groupby,您可以使用分组对象。

这可以实现以下功能:

df.index.to_series().groupby(df['A']).unique()
Run Code Online (Sandbox Code Playgroud)

输出:

A
bar    [1, 2, 4]
foo       [0, 3]
dtype: object
Run Code Online (Sandbox Code Playgroud)
获取唯一 B 值的索引:
A
bar    [1, 2, 4]
foo       [0, 3]
dtype: object
Run Code Online (Sandbox Code Playgroud)