0

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks wwnde, can I use column number instead of column name? since in my working code, I have a 100 columns, that is why I just use iloc[2:]. Thanks for help
Yes, do you mean df.iloc[df[df['name']=='eric'].index,2] *=10?
wow, you save me my whole night, I am sittting here for 4 hours now it is solved. It is my first time know I can use df[df['name']=='eric'].index. I learnt it hard today. Thank you! I really appreciate it. I am so happy now! Have a great night!
wwnde, I appreciate it. But I still don't understand why my previous approach is not working by doing df[df['name']=='eric'].iloc[:,2:]=df[df['name']=='eric'].iloc[:,2:]*10
Lets do some tests type(df[df['name']=='eric'].iloc[:,2:]) is a dataframe. Meaning, this command create a new dataframe that you end up updating. You do not update the original df. Makes sense? On the other hand, `type(df.iloc[df[df['name']=='eric'].index,2])' creates a series meaning you are subsetting and then updating
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.