首页 > 解决方案 > pythonic和uFunc-y方式将pandas列变成“增加”索引?

问题描述

假设我有一个像这样的熊猫 df:

Index   A     B
0      foo    3
1      foo    2
2      foo    5
3      bar    3
4      bar    4
5      baz    5

像这样添加列的快速方法是什么:

Index   A     B    Aidx
0      foo    3    0
1      foo    2    0
2      foo    5    0
3      bar    3    1
4      bar    4    1
5      baz    5    2

即为每个唯一值添加一个增加的索引?

我知道我可以使用df.unique(),然后使用 dict 并enumerate创建查找,然后应用该字典查找来创建列。但我觉得应该有更快的方法,可能涉及groupby一些特殊功能?

标签: pythonpandas

解决方案


一种方法是使用ngroup. 请记住,您必须确保您的 groupby 没有利用组来获得所需的输出,因此请设置sort=False

df['Aidx'] = df.groupby('A',sort=False).ngroup()
>>> df
   Index    A  B  Aidx
0      0  foo  3     0
1      1  foo  2     0
2      2  foo  5     0
3      3  bar  3     1
4      4  bar  4     1
5      5  baz  5     2

推荐阅读