Gcube
Gcube

Reputation: 47

Change specific values in dataframe

I have df like this:

Name   Value       NUM_SC

A      1000        421

B      2000        127

C      3000        511

D      2000        718

E      1500        511 (may duplicate)

And I would like to multiply some Values by (-1) based on their NUM_SC. For example, for 511 and 127 in NUM_SC multiply Value by (-1). What worked for me is:

for i in negative_sc:
    for j in range(76818):
        if df.NUM_SC[j] == i:
            df.Values[j] *= (-1)

where negative_sc containts NUM_SC for which I would like multiply Value by (-1). In this example negative_sc = (511,127).

But this method takes a lot of time. I tried something like this:

for i in negative_sc:
   df[df.NUM_SC == i].Values *= (-1)

But this produced error and didn't yield any results.

What is the best way to handle tasks like this? Change values in one column based on values in another column

Thanks a lot!

Upvotes: 0

Views: 42

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150825

You should not chain [ ] and .column_name. So both df.Values[j] *= -1 and df[df.NUM_SC == i].Values *= -1 don't work. See this document for details.

Instead do:

df.loc[df.NUM_SC.isin(negative_sc), 'Values'] *= -1

Upvotes: 1

sushanth
sushanth

Reputation: 8302

try this, using isin create a mask for columns you would like need to negate.

negative_sc = [511, 127]

mask = df['NUM_SC'].isin(negative_sc)

df.loc[mask, 'Value'] = df.loc[mask, 'Value'] * -1

Upvotes: 0

Related Questions