Add auto-increment column on pandas multi-index

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Add auto-increment column on pandas multi-index



I have the following multi-index panda below. I am trying to create:



However I am unsure how I would be able to do this. Any pointers would help



Multi-index before:


duration_in_status
lob project_rank
Commodities CM LOB 2.0
Index Book Migration 25.0
Cross Platform CM LOB 0.0
CSAVA 16.0
Calypso Migration 0.0
EMD / Delta One 0.0
FRTB 68.0
Index Book Migration 1.0
Instruments 3.0
KOJAK 0.0
LOB BOW 324.0
Non-Trading 0.0
Notes Workflow 23.0
PROD 0.0
Result Service 53.0
Tech Debt 96.0
Interest Rates LOB BOW 0.0
Other Notes Workflow 0.0
Treasury 2B2 1.0



Acceptance Criteria Result:



enter image description here





what does the data look like before its in the multiindex?
– loegare
26 mins ago




1 Answer
1



I would just use groupby and apply.


# assuming "df" is the variable containing the data as you showed in the question...

import numpy as np

def group_function(sub_dataframe):
sub_dataframe["proj_num"] = np.arange(df.shape[0]) + 1
sub_dataframe["depth"] = df.shape[0]
return sub_dataframe

df = df.reset_index().groupby("lob").apply(group_function)
df = df.set_index(["lob","project_rank"])



In case you are creating previously creating the multiindex yourself, you could do this before that. That way you wouldn't need the reset_index and could create it only once.


# in that case, something like this should work.
df = df.groupby("lob").apply(group_function). df.set_index(["lob","project_rank"])






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

'Series' object is not callable Error / Statsmodels illegal variable name