Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: How to access the value of the index

Tags:

python

pandas

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.

like image 723
Ross R Avatar asked Nov 14 '13 23:11

Ross R


People also ask

How do I get pandas index value?

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.

How do I select a specific index in pandas?

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.

How do you access a DataFrame using an index?

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.


Video Answer


1 Answers

df["idx1_mod"] = df.index.get_level_values(0).values + 100
like image 155
HYRY Avatar answered Oct 25 '22 12:10

HYRY