- Get link
- X
- Other Apps
In Python, replace specific column values except the first row in a DataFrame.
I'm using pandas and have put some data into a DataFrame, as shown below. My data looks like this: that the Data2 and Data3 have the same repeated values, thus what I want to do is maintain one value for Data2 and Data3 for the same Date_x column and replace the rest with zero.
(Below table is visible correctly in desktop mode)
Date_x | Data2 | Data3 | Month | Date_y | |
---|---|---|---|---|---|
0 | 2021-07-03 | 2000 | 1400 | 7 | 2021-07-03 |
1 | 2021-07-03 | 2000 | 1400 | 7 | 2021-07-10 |
2 | 2021-07-03 | 2000 | 1400 | 7 | 2021-07-17 |
3 | 2021-07-03 | 2000 | 1400 | 7 | 2021-07-24 |
4 | 2021-07-03 | 2000 | 1400 | 7 | 2021-07-31 |
5 | 2021-08-07 | 1000 | 1500 | 8 | 2021-08-07 |
6 | 2021-08-07 | 1000 | 1500 | 8 | 2021-08-14 |
7 | 2021-08-07 | 1000 | 1500 | 8 | 2021-08-21 |
8 | 2021-08-07 | 1000 | 1500 | 8 | 2021-08-28 |
9 | 2021-09-04 | 3000 | 1600 | 9 | 2021-09-04 |
10 | 2021-09-04 | 3000 | 1600 | 9 | 2021-09-11 |
11 | 2021-09-04 | 3000 | 1600 | 9 | 2021-09-18 |
12 | 2021-09-04 | 3000 | 1600 | 9 | 2021-09-25 |
13 | 2021-10-02 | 4000 | 1700 | 10 | 2021-10-02 |
14 | 2021-10-02 | 4000 | 1700 | 10 | 2021-10-0 |
Steps for Code
- First, I executed the block for DataFrame length.
- The current Index value of Date x was then compared to the prior Index value of Date x.
- If the condition is true, it replaces the Data2 and Data3 values in the DataFrame with 0.
- If the condition fails, the case is passed.
Python Code
for i in range(len(df_merged)-1):
if df_merged['Date_x'][i] == df_merged['Date_x'][i+1]:
df_merged['Data2'][i+1]=0
df_merged['Data3'][i+1]=0
else:
pass
Final result after execution
(Below table is visible correctly in desktop mode)
|
Date_x | Data2 | Data3 | Month | Date_y |
---|---|---|---|---|---|
0 | 2021-07-03 | 2000 | 1400 | 7 | 2021-07-03 |
1 | 2021-07-03 | 0 | 0 | 7 | 2021-07-10 |
2 | 2021-07-03 | 0 | 0 | 7 | 2021-07-17 |
3 | 2021-07-03 | 0 | 0 | 7 | 2021-07-24 |
4 | 2021-07-03 | 0 | 0 | 7 | 2021-07-31 |
5 | 2021-08-07 | 1000 | 1500 | 8 | 2021-08-07 |
6 | 2021-08-07 | 0 | 0 | 8 | 2021-08-14 |
7 | 2021-08-07 | 0 | 0 | 8 | 2021-08-21 |
8 | 2021-08-07 | 0 | 0 | 8 | 2021-08-28 |
9 | 2021-09-04 | 3000 | 1600 | 9 | 2021-09-04 |
10 | 2021-09-04 | 0 | 0 | 9 | 2021-09-11 |
11 | 2021-09-04 | 0 | 0 | 9 | 2021-09-18 |
12 | 2021-09-04 | 0 | 0 | 9 | 2021-09-25 |
Please if you have any question regarding the same or have any better solution please share it in comment section.