Python/Pandas - 根据列值向 DataFrame 添加计数器

标签 python pandas

使用 Python,我有一个 panda 数据框

A B 
1 red
2 blue
3 green
4 red
5 green
6 orange
7 red

我想根据 B 中的值创建一个带有增量计数器的列。即解析为

A B      C
1 red    1
2 blue   1
3 green  1
4 red    2
5 green  2
6 orange 1
7 red    3

最佳答案

按每种颜色分组,然后使用 cumcount 方法。

df['C'] = df.groupby('B').cumcount() + 1

   A       B  C
0  1     red  1
1  2    blue  1
2  3   green  1
3  4     red  2
4  5   green  2
5  6  orange  1
6  7     red  3

关于Python/Pandas - 根据列值向 DataFrame 添加计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42128514/

相关文章:

python - SQLAlchemy 文本函数是否暴露于 SQL 注入(inject)?

python - 在 Pandas 中将字符串转换为小写

python - 如何从 sklearn TruncatedSVD 对象中获取特征名称?

python - 重新采样/时间分组到特定的时间跨度/周期

python - 使用文本文件中的 header 信息来组织数据框

python - 检查列表中的所有值是否大于某个数字

python - 无法使用 pyenv ipython 笔记本导入 matplotlib

python - 如何在 Python 中的 POST 请求中将查询作为正文发送

python - NA 的 bool 值太模糊

python - Pandas 数据框的自定义函数中的 Forex_python