I have a dataframe as below
JavaScript
x
9
1
A B C D E F G H I
2
1 2 3 4 5 6 7 8 9
3
1 2 3 4 5 6 7 8 9
4
1 2 3 4 5 6 7 8 9
5
1 2 3 4 5 6 7 8 9
6
1 2 3 4 5 6 7 8 9
7
1 2 3 4 5 6 7 8 9
8
1 2 3 4 5 6 7 8 9
9
I want to multiply every 3rd column after the 2 column in the last 2 rows by 5 to get the ouput as below.
How to acomplish this?
JavaScript
1
9
1
A B C D E F G H I
2
1 2 3 4 5 6 7 8 9
3
1 2 3 4 5 6 7 8 9
4
1 2 3 4 5 6 7 8 9
5
1 2 3 4 5 6 7 8 9
6
1 2 3 4 5 6 7 8 9
7
1 10 3 4 25 6 7 40 9
8
1 10 3 4 25 6 7 40 9
9
I am able to select the cells i need with df.iloc[-2:,1::3]
which results in the df as below but I am not able to proceed further.
JavaScript
1
4
1
B E H
2
2 5 8
3
2 5 8
4
I know that I can select the same cells with loc
instead of iloc
, then the calcualtion is straign forward, but i am not able to figure it out.
The column names & cell values CANNOT Be used since these change (the df here is just a dummy data)
Advertisement
Answer
You can assign back to same selection of rows/ columns like:
JavaScript
1
13
13
1
df.iloc[-2:,1::3] = df.iloc[-2:,1::3].mul(5)
2
#alternative
3
#df.iloc[-2:,1::3] = df.iloc[-2:,1::3] * 5
4
print (df)
5
A B C D E F G H I
6
0 1 2 3 4 5 6 7 8 9
7
1 1 2 3 4 5 6 7 8 9
8
2 1 2 3 4 5 6 7 8 9
9
3 1 2 3 4 5 6 7 8 9
10
4 1 2 3 4 5 6 7 8 9
11
5 1 10 3 4 25 6 7 40 9
12
6 1 10 3 4 25 6 7 40 9
13