Home > Back-end >  how to modify dataframe values using filter
how to modify dataframe values using filter

Time:01-09

I am trying to modify some cells' values by multiplying by 10 . and it doesn't work. Here is a simple code example: Thank you so much for help

a={'name':['john','eric','kate'],'buy':[100,50,200],'sell':[20,30,40]}
df=pd.DataFrame(a)
df

    name    buy sell
0   john    100 20
1   eric    50  30
2   kate    200 40

df[df['name']=='eric'].iloc[:,2:]=df[df['name']=='eric'].iloc[:,2:]*10
df

name    buy sell
0   john    100 20
1   eric    50  30
2   kate    200 40

but if I do this by modifying all the row values, then it is fine, so what is the problem of above code when using row filtering? Thank you so much for your help


df.iloc[:,2:]=df.iloc[:,2:]*10
df

name    buy sell
0   john    100 200
1   eric    50  300
2   kate    200 400

CodePudding user response:

Lets try

df.loc[df['name']=='eric',['buy','sell']] *=10

How it works

.iloc is an integer accessor. it accesses by referencing columns using their integer axis. So df.iloc[:,2:] is a selection of the second column index which is sell

You can achieve the same using

df.iloc[df[df['name']=='eric'].index,2] *=10
  •  Tags:  
  • Related