首页 > 解决方案 > create incremental number from 1 in pandas

问题描述

I want to add a new column in my dataframe where the new column is an incremental number started from 0

type   value
a       25
b       23
c       33
d       31

I expect my dataframe would be:

type   value   id
a       25     1
b       23     2
c       33     3
d       31     4

beside the id column, I also want to add a new column: status_id where from number 1 to 2 is called foo and from number 3 to 4 is called bar. I expect the full dataframe would be like:

type   value   id   status_id
a       25     1      foo
b       23     2      foo
c       33     3      bar
d       31     4      bar

How can I do this with pandas? Thanks in advance

标签: pythonpandas

解决方案


我们可以试试cut

df['status_id'] = pd.cut(df.id,[0,2,4],labels=['foo','bar'])
df
  type  value  id status_id
0    a     25   1       foo
1    b     23   2       foo
2    c     33   3       bar
3    d     31   4       bar

推荐阅读