将后缀添加到重复的索引值 [英] Adding suffix to duplicate index values

查看:42
本文介绍了将后缀添加到重复的索引值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个df:

-0.01   -0.029064
-0.01   -0.032876
-0.01   -0.040795
-0.02   -0.027003
-0.02   -0.0315

需要与另一帧保持一致,但是会收到错误无法从重复的轴重新索引".我想要的是这样的df:

Need to concat this with another frame, but get the error "cannot reindex from a duplicate axis". What I'd like is a df like this:

-0.01   -0.029064
-0.011   -0.032876
-0.012   -0.040795
-0.02   -0.027003
-0.021   -0.031589

(注意:在每个重复索引之后添加后缀)

(note: added suffixes after each duplicate index)

推荐答案

要获取这些累计计数,请使用groupby + cumcount.

To get these cumulative counts, use groupby + cumcount.

v = df.groupby(df.index)\
      .cumcount()\
      .astype(str)\
      .str.replace('0', '')\
      .values

v 
array(['', '1', '2', '', '1'], dtype=object)

与索引串联:

df.index = (df.index.values.astype(str) + v).astype(float)
df

           Value
-0.010 -0.029064
-0.011 -0.032876
-0.012 -0.040795
-0.020 -0.027003
-0.021 -0.031500

这篇关于将后缀添加到重复的索引值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆