繁体   English   中英

根据另一列特定值的每次出现在熊猫中添加索引

[英]Add index in pandas based on each occurance of another column specific value

我有一个像这样的数据框:

category name   age 
parent  harry   29
child   smith   12
parent  sally   41
child   david   19
child   mike    16

我想根据类别列值“父”的每次出现添加一个列来对家庭进行分组(数据框按顺序排列)。 如:

category name   age  family_id
parent  harry   29     0
child   smith   12     0
parent  sally   41     1
child   david   19     1
child   mike    16     1

我试图让 family_id 成为一个递增的整数。

我已经尝试了一堆 group_by 并且目前正在尝试编写我自己的应用函数,但是它非常慢并且没有按预期工作。 我一直无法找到一个示例,该示例在每次出现相同值时根据列值行进行分组。

如果category列等于parentcumsum ,则可以使用eq进行匹配, sub是减去 1,因为 cumsum 在这里从 1 开始:

df['family_id'] = df['category'].eq('parent').cumsum().sub(1)
print(df)

  category   name  age  family_id
0   parent  harry   29          0
1    child  smith   12          0
2   parent  sally   41          1
3    child  david   19          1
4    child   mike   16          1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM