chrisfs
chrisfs

Reputation: 6333

How to subtract 1 from each value in a column in Pandas

I think this should be a simple problem, but I can't find a solution.

Within a subset of rows in a dataframe, I need to decrement the value of each item in a column by 1. I have tried various approaches, but the values continue to be unchanged. Following another entry on SO, I tried

def minus1(x):
    x =x-1
    return x

pledges[pledges.Source == 'M0607'].DayOFDrive = pledges[pledges.Source == 'M0607'].DayOFDrive.map(minus1)

When I typed

pledges[pledges.Source == 'M0607'].DayOFDrive

to check it, the original unchanged data came back. I have also tried

pledges[pledges.Source == 'M0607'].DayOFDrive = pledges[pledges.Source == 'M0607'].DayOFDrive-1

which also does nothing.

How can I reduce all the values in a column by 1 for a subset of rows ?

Upvotes: 2

Views: 4447

Answers (1)

John Zwinck
John Zwinck

Reputation: 249502

If this returns the data you want to modify:

pledges[pledges.Source == 'M0607'].DayOFDrive

Then try modifying it this way:

pledges[pledges.Source == 'M0607'].DayOFDrive -= 1

Upvotes: 3

Related Questions