python - 熊猫,根据其他列创建“订单”列
问题描述
我有两列数据框,集群标题和它们所属的章节。我想创建第三列,包含该集群在章节中的“顺序”或位置。
所以,我想打开以下数据框:
cluster_title, chapter
"rabbits", 1
"horses", 1
"cows", 1
"trains", 2
"airplanes", 2
"ships", 2
"carrot", 3
"potato", 3
"tomato", 3
变成这样:
cluster_title, chapter, position_in_chapter,
"rabbits", 1, 1
"horses" 1, 2
"cows", 1, 3
"trains", 2, 1
"airplanes", 2, 2
"ships", 2, 3
"carrot", 3, 1
"potato", 3, 2
"tomato", 3, 3
我尝试使用group_by
函数来接近它并以某种方式使用索引,但要么我遗漏了一些明显的东西(很可能),要么这是错误的方法,因为生成的对象需要额外的步骤,这似乎把我带到了错误的方向。
有人能指出我正确的方向吗?
解决方案
尝试使用groupby
和cumcount
:
df["position_in_chapter"] = df.groupby("chapter").cumcount()+1
>>> df
cluster_title chapter position_in_chapter
0 rabbits 1 1
1 horses 1 2
2 cows 1 3
3 trains 2 1
4 airplanes 2 2
5 ships 2 3
6 carrot 3 1
7 potato 3 2
8 tomato 3 3
推荐阅读
- swift - 摆脱标签视图中的导航栏
- macos - Selenium Chrome 驱动程序在 macOS 上崩溃
- joomla3.0 - 如何将子表单的(Joomla)管理布局从表格模式更改为 div 模式?
- django - 写入文件,然后通过 api 发送
- android - Android以编程方式执行shell命令(非root)
- vb.net - 在单元格值更改时重新排序 Datagridview
- html - MVC 站点“缓存”问题
- c++ - 计算浮点余数的最佳方法
- java - 如何为 BinaryTree 编写 left() 和 right() 方法
班级 - javascript - 从 HTML 数据运行 Javascript