0

I need to create a new index from scratch i and then use it as an inner index part of a multi index. I am using an example df below.

#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 need i to reset i for each group of a.

the desired results is the following:

    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

then I need to create multi index of a and i

df.set_index(["a","i"], inplace=True)
Sami Al-Subhi
  • 4,406
  • 9
  • 39
  • 66

1 Answers1

0

There is 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
BENY
  • 317,841
  • 20
  • 164
  • 234