In [1]:
import pandas as pd

In [2]:
pd.__version__


Out[2]:
'0.24.2'

loc

locate by label


In [157]:
df_default_index = pd.DataFrame({
    'name':['john','mary','peter','nancy','gary'],
    'age':[22,33,27,22,31],
    'state':['AK','DC','CA','CA','NY']
})
df_default_index


Out[157]:
name age state
0 john 22 AK
1 mary 33 DC
2 peter 27 CA
3 nancy 22 CA
4 gary 31 NY

In [158]:
df_default_index.loc[[0]]


Out[158]:
name age state
0 john 22 AK

In [159]:
df_default_index.loc[[2,3]]


Out[159]:
name age state
2 peter 27 CA
3 nancy 22 CA

In [130]:
df_name_index = pd.DataFrame(
    index=['john','mary','peter','nancy','gary'],
    data={
        'age':[22,33,27,22,31],
        'state':['AK','DC','CA','CA','NY']
    }
)

In [131]:
df_name_index


Out[131]:
age state
john 22 AK
mary 33 DC
peter 27 CA
nancy 22 CA
gary 31 NY

In [133]:
df_name_index.loc[['peter']]


Out[133]:
age state
peter 27 CA

In [143]:
df_name_index.loc[['john']]


Out[143]:
age state
john 22 AK

iloc

locate by position


In [134]:
df_name_index.iloc[[0]]


Out[134]:
age state
john 22 AK

In [141]:
df_name_index.iloc[[2,3,4]]


Out[141]:
age state
peter 27 CA
nancy 22 CA
gary 31 NY

In [135]:
df_default_index.iloc[[0]]


Out[135]:
name age state
0 john 22 AK

In [142]:
df_default_index.iloc[[2,3,4]]


Out[142]:
name age state
2 peter 27 CA
3 nancy 22 CA
4 gary 31 NY

set value to individual cell

must use loc


In [155]:
df_set = pd.DataFrame({
    'name':['john','mary','peter','nancy','gary'],
    'age':[22,33,27,22,31],
    'state':['AK','DC','CA','CA','NY']
})
df_set


Out[155]:
name age state
0 john 22 AK
1 mary 33 DC
2 peter 27 CA
3 nancy 22 CA
4 gary 31 NY

In [156]:
df_set.loc[0,'name'] = 'bartholomew'

df_set.loc[3, 'age'] = 39

df_set


Out[156]:
name age state
0 bartholomew 22 AK
1 mary 33 DC
2 peter 27 CA
3 nancy 39 CA
4 gary 31 NY

In [148]:
df_name_index.loc['john','age'] = 99
df_name_index


Out[148]:
age state
john 99 AK
mary 33 DC
peter 27 CA
nancy 22 CA
gary 31 NY

settingwithcopywarning

bad:


In [53]:
df_over_30_years = df[df['age']>30]
df_over_30_years


Out[53]:
name age state
1 mary 33 DC
4 gary 31 NY

In [54]:
df_over_30_years['new_column'] = 'some_value'


/home/felipe/venv36/lib/python3.6/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  """Entry point for launching an IPython kernel.

good:


In [49]:
df_over_30_years = df.copy()[df['age']>30]
df_over_30_years


Out[49]:
name age state
1 mary 33 DC
4 gary 31 NY

In [50]:
df_over_30_years['new_column'] = 'some_value'

In [51]:
df_over_30_years


Out[51]:
name age state new_column
1 mary 33 DC some_value
4 gary 31 NY some_value