7

I have a dataframe and would like to use the values in the index to create another column.
For instance:

df=pd.DataFrame({'idx1':range(0,5), 'idx2':range(10000,10005), 'value':np.random.randn(5)})
df.set_index(keys=['idx1','idx2'], inplace=True)
print df

               value
idx1 idx2           
0    10000 -1.470367
1    10001  0.260693
2    10002 -0.732319
3    10003 -0.116977
4    10004  1.106644

I'd like to do something like this:

df['idx1_mod']= df['idx1'] + 100

(Actually, I want to do more complicated things, but basically I need the value of the index.)

Right now I'm resorting to reseting the index (to get the index fields as columns), doing my calcs with access to the columns, and then re-creating the index. I'm sure I'm missing something obvious, but I've looked a ton and keep missing it!

Note - I also tried df.iterrows(), but it seems that gives a copy of the row and doesn't let me update the original dataframe.

3 Answers 3

10
df["idx1_mod"] = df.index.get_level_values(0).values + 100
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. My actual use case requires more than one field, but this was the clue I needed. For the next questioner, this works for multiple fields: df['idx_mod'] = df.index.map(lambda idx: someFunc(idx[0],idx[1]))
3

Try this:

for idx in range(len(df)):
    df['idx1_mod'][idx] = df.index[idx][0] + 100 

Comments

3

You can use drop=False when setting the index to preserve your keys as columns. This should work:

df.set_index(keys=['idx1','idx2'], inplace=True, drop=False)
df['idx1_mod'] = df['idx'] + 100

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.