Pandas: Index updating and changing value accessed by location

dataframe, indexing, pandas, python

Solution

1) I do not understand why the indexing is not automatically updated after I modify the dataframe.

If you want to reset the index after removing/adding rows you can do this:

df = df[df.B != 'three'] # remove where B = three
df.reset_index(drop=True)

       B    amount  id
0    one    -1.176137    1
1    one     0.434470    2
2    two    -0.887526    3
3    two     0.126969    5
4    one     0.090442    7
5    two    -1.511353    8

Indexes are meant to label/tag/id a row... so you might think about making your 'id' column the index, and then you'll appreciate that Pandas doesn't 'automatically update' the index when deleting rows.

df.set_index('id')

       B    amount
id      
1    one    -0.410671
2    one     0.092931
3    two    -0.100324
4    three   0.322580
5    two    -0.546932
6    three  -2.018198
7    one    -0.459551
8    two     1.254597

2) I want to be able to set the B column of the 5th element of df to 'three'. But df.iloc[5]['B'] = 'three' does not do that. I checked on the manual but it does not cover how to change a specific cell value accessed by location.

Jeff already answered this...

Problem

I have two index-related questions on Python Pandas dataframes. ``` import pandas as pd import numpy as np df = pd.DataFrame({'id' : range(1,9), 'B' : ['one', 'one', 'two', 'three', 'two', 'three', 'one', 'two'], 'amount' : np.random.randn(8)}) df = df.ix[df.B != 'three'] # remove where B = three df.index >> Int64Index([0, 1, 2, 4, 6, 7], dtype=int64) # the original index is preserved. ``` 1) I do not understand why the indexing is not automatically updated after I modify the dataframe. Is there a way to automatically update the indexing while modifying a dataframe? If not, what is the most efficient manual way to do this? 2) I want to be able to set the `B` column of the 5th element of `df` to 'three'. But `df.iloc[5]['B'] = 'three'` does not do that. I checked on the manual but it does not cover how to change a specific cell value accessed by location. If I were accessing by row name, I could do: `df.loc[5,'B'] = 'three'` but I don't know what the index access equivalent is. P.S. Link1 and link2 are relevant answers to my second question. However, they do not answer my question.

Original source

Related problems