python - 从头开始创建二级/内部索引
问题描述
我需要从头开始创建一个新索引i
,然后将其用作多索引的内部索引部分。我正在使用下面的示例 df。
#example df
df = pd.DataFrame({"a":[11,11,22,22,22,33],"b":[1,2,3,4,5,6]})
# creating the i index
df["i"]=0
def createIndex(grouped_df):
newIndex = list(range(0, len(grouped_df.index)))
grouped_df["i"]=newIndex
return grouped_df
df.groupby("a").apply(createIndex)
print(df)
a b i
0 11 1 0
1 11 2 0
2 22 3 0
3 22 4 0
4 22 5 0
5 33 6 0
i
我需要我为每组重置a
。
期望的结果如下:
a b i
0 11 1 0
1 11 2 1
2 22 3 0
3 22 4 1
4 22 5 2
5 33 6 0
然后我需要创建a
和的多索引i
df.set_index(["a","i"], inplace=True)
解决方案
有cumcount
df['i']=df.groupby('a').cumcount()
df
a b i
0 11 1 0
1 11 2 1
2 22 3 0
3 22 4 1
4 22 5 2
5 33 6 0
推荐阅读
- java - 通过带有参数表的注释选择 CDI bean
- javascript - 绑定数组的对象数组
- android - CardViews 未显示在 RecyclerView 中
- sql - 列被随机删除Postgres?
- c# - 检测 .NET Framework 功能和 WCF 服务
- r - 不同目录中的同时 R 会话
- javascript - Angular 6如何在表单内制作所有输入的不可编辑元素
- java - 是否可以创建一个哈希映射,其中每个值都是对对象有不同作用的方法
- windows-7 - 是否可以使用 Windows cmd 在 Notepad++ 中输入 SecurePad 插件的密码?[编辑]
- eclipse - 从 Github 父/子 pom 在 Eclipse 中创建新项目?