Home > Enterprise >  Python pandas how to replace zeros in a column between values with these same values
Python pandas how to replace zeros in a column between values with these same values

Time:09-07

I have a csv file in which such a column is calculated:

Combined
0
0
1
0
0
0
2
0
0
0
3
0
0
0
0
-1
0
0
0
0
-2
0
0
0
0
-3
0
0
0
1

I would like to change the values in it so that when, for example, the value -1 appears, all zeros up to the value -2 turn into -1, which would turn out something like this

Combined
0
0
1
1
1
1
2
2
2
2
3
3
3
3
3
-1
-1
-1
-1
-1
-2
-2
-2
-2
-2
-3
-3
-3
-3
1

I combine it into class functions in this way

cols = ['Answers', 'step', 'step2']
        df['combined'] = df[cols].apply(lambda row: ''.join(row.values.astype(str)), axis=1)
        df['combined'] = df['combined'].str.replace('0.000', 'O',regex=True)
        df['combined'] = df['combined'].map(lambda x: x.lstrip('0.0').rstrip('.000'))
        df['combined'] = df['combined'].str.replace('O', '0')

For the sake of explanation ! At the beginning of this csv there is always a pair of zeros, but after them either -1 or 1 always comes and then it always goes depending on the first number either -2 or 2 and the three comes exactly the same depending on the second number either -3 or 3 And after its cycle repeats and also depending on the three, either -1 or 1.

CodePudding user response:

If need forward filling 0 to previous non 0 values use:

df['Combined'] = df['Combined'].replace(0, np.nan).ffill().fillna(0).astype(int)
print (df)
   Combined
0         0
1         0
2         1
3         1
4         1
5         1
6         2
7         2
8         2
9         2
10        3
11        3
12        3
13        3
14        3
15       -1
16       -1
17       -1
18       -1
19       -1
20       -2
21       -2
22       -2
23       -2
24       -2
25       -3
26       -3
27       -3
28       -3
29        1
  • Related