python - 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
解决方案
我们可以试试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
推荐阅读
- javascript - 如何输出表单值以提醒 JavaScript
- qt - QTreeView,当鼠标悬停在一行上时如何调用动作?
- javascript - 如何使用 JavaScript 切换 CSS 中的类?
- bash - 在用于 greping 文件的 for 循环和使用文件查询 greping 文件之间有什么更快/更好的做法?
- python - 我的代码没有打印“未找到匹配项”,为什么?
- arrays - Swift - 向字典中的数组添加值
- java - 仅从 GitHub API 返回选定的字段
- javascript - 有没有办法可以预览我的 html 文件?
- javascript - 如何使用 i18n 制作具有漂亮 URL 的网站?
- oracle-apex - ords 独立服务器的 oracle apex ssl 配置