Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Setting value using both loc and iloc pandas

We have data, which is represented below:

import pandas as pd
import numpy as np

d = {'shift_city_id': [1, 1,2,3,3,3,1], 'closest_city_id': [np.nan, np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]}
df = pd.DataFrame(data=d)
df

  shift_city_id  closest_city_id
0      1           NaN
1      1           NaN
2      2           NaN
3      3           NaN
4      3           NaN
5      3           NaN
6      1           NaN

The goal is to input specific values in a cell with particular city_id, one by one. So I try this:

df.loc[lambda x: (x['shift_city_id']==3),'closest_city_id'].iloc[0]=3
df.loc[lambda x: (x['shift_city_id']==3),'closest_city_id'].iloc[1]=4
df.loc[lambda x: (x['shift_city_id']==3),'closest_city_id'].iloc[2]=5

and get no change at all in dataframe, np.nan is still there. While the result should be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    shift_city_id   closest_city_id
0     1                 NaN
1     1                 NaN
2     2                 NaN
3     3                 3
4     3                 4  
5     3                 5
6     1                 NaN

What can solve the problem?

>Solution :

You could do:

df.loc[lambda x: (x['shift_city_id']==3),'closest_city_id'] = [3,4,5]

which gives the wanted output:

enter image description here

To understand the different behaviour of the assignation, I defer to these detailed answers

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading