Python 从头开始创建辅助/内部索引

Python 从头开始创建辅助/内部索引,python,python-3.x,pandas,pandas-groupby,Python,Python 3.x,Pandas,Pandas Groupby,我需要从头创建一个新索引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
,然后将其用作多索引的内部索引部分。我正在使用下面的示例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
我需要为每组
a
重置
I

预期结果如下:

    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