您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

我想向pandas数据框添加新索引

我想向pandas数据框添加新索引

用途ngroup

对于新列 index

df[‘index’] = df.groupby(‘date’, sort=False).ngroup() + 1 print (df) date price neg_vol pos_vol index 0 2017-10-17 01:00:00 51.88 11 4 1 1 2017-10-17 01:00:00 51.89 10 2 1 2 2017-10-17 01:00:00 51.90 16 27 1 3 2017-10-17 01:00:00 51.91 1 10 1 4 2017-10-17 01:05:00 51.87 12 0 2 5 2017-10-17 01:05:00 51.88 0 12 2 6 2017-10-17 01:10:00 51.87 8 0 3 7 2017-10-17 01:10:00 51.88 0 5 3 8 2017-10-17 01:15:00 51.87 12 0 4 9 2017-10-17 01:15:00 51.88 0 8 4 10 2017-10-17 01:20:00 51.87 6 0 5

用于新索引

df.index = df.groupby(‘date’, sort=False).ngroup() + 1 print (df) date price neg_vol pos_vol 1 2017-10-17 01:00:00 51.88 11 4 1 2017-10-17 01:00:00 51.89 10 2 1 2017-10-17 01:00:00 51.90 16 27 1 2017-10-17 01:00:00 51.91 1 10 2 2017-10-17 01:05:00 51.87 12 0 2 2017-10-17 01:05:00 51.88 0 12 3 2017-10-17 01:10:00 51.87 8 0 3 2017-10-17 01:10:00 51.88 0 5 4 2017-10-17 01:15:00 51.87 12 0 4 2017-10-17 01:15:00 51.88 0 8 5 2017-10-17 01:20:00 51.87 6 0

一个解决方案是factorize

df['index'] = pd.factorize(df['date'])[0] + 1
df.index = pd.factorize(df['date'])[0] + 1
其他 2022/1/1 18:34:59 有571人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶