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.
To get the index of a Pandas DataFrame, call DataFrame. index property. The DataFrame. index property returns an Index object representing the index of this DataFrame.
Select Rows & Columns by Name or Index in Pandas DataFrame using [ ], loc & iloc. Indexing in Pandas means selecting rows and columns of data from a Dataframe.
DataFrame provides indexing label iloc for accessing the column and rows by index positions i.e. It selects the columns and rows from DataFrame by index position specified in range. If ':' is given in rows or column Index Range then all entries will be included for corresponding row or column.
df["idx1_mod"] = df.index.get_level_values(0).values + 100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With