首页 > 解决方案 > 从头开始创建二级/内部索引

问题描述

我需要从头开始创建一个新索引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)

标签: pythonpython-3.xpandaspandas-groupby

解决方案


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

推荐阅读