Lorenz
Lorenz

Reputation: 306

Pandas Dataframe: Update values in a certain columns for last n rows

In the example below, I want to update column C for the last 3 rows to the value 0.

Source Dataframe

A B C D E
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5

Target Dataframe

A B C D E
1 1 1 1 1
2 2 2 2 2
3 3 0 3 3
4 4 0 4 4
5 5 0 5 5

I tried something like

df.tail(3)['C']=0

but it does not work. Any idea?

Upvotes: 3

Views: 3601

Answers (2)

heena bawa
heena bawa

Reputation: 828

You can use:

df.iloc[-3:]['C'] = 0

Output:

   A  B  C  D  E
0  1  1  1  1  1
1  2  2  2  2  2
2  3  3  0  3  3
3  4  4  0  4  4
4  5  5  0  5  5

Other way:

df[-3:]['C'] = 0

Upvotes: 1

rafaelc
rafaelc

Reputation: 59274

You can settle for

df.loc[df.tail(3).index, 'C'] = 0

Upvotes: 6

Related Questions