python - 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
一些特殊功能?
解决方案
一种方法是使用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
推荐阅读
- node.js - POST 请求返回 404(未找到);Next-authentication/Next.js
- jquery - 我想使用 Jquery validate 插件进行验证,但它不起作用
- html - flex-basis 的列边距为 33.33%?
- python - 使用 tkinter,.get() 方法似乎不适用于我的代码
- python - Visual Studio 2019、Python 和神经元模拟器
- python - 文件内容的匹配模式和出现次数
- html - 使用 CSS Grid 的动态行
- java - 将元素添加到多个线程中的列表时被跳过
- c++ - SDL 窗口在移动时消失?
- newline - 如何在变量之间有换行符?