Home > other >  replace row in specific sequence (pandas dataframe)
replace row in specific sequence (pandas dataframe)

Time:12-19

I'm trying to replace the value at the specific row under the condition

Here is the sample dataframe:

import pandas as pd

# create a Series with the given data
s = pd.Series([1, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 1, 0, -1, 0, 0, 1, 0, 0, -1, 1, -1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 1, -1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0], name='position_short')

# create a dataframe with the Series as the only column
df = pd.DataFrame(s)

# set the index of the dataframe to the bar numbers
df.index = range(7, 108)

It looks like this:

Bar numbers
7      1
8     -1
9      0
10     0
11     0
12     1
13     0
14     0
15    -1
16     0
17     0
18     0
19     0
20     0
21     0
22     0
23     0
24     0
25     0
26     0
27     0
28     0
29     0
30     0
31     0
32     1
33     0
34     0
35     0
36    -1

I'm trying to replace every value which is located 24 rows of value 1 with -1.

Here is the desired output:

Bar numbers
7      1
8     -1
9      0
10     0
11     0
12     1
13     0
14     0
15    -1
16     0
17     0
18     0
19     0
20     0
21     0
22     0
23     0
24     0
25     0
26     0
27     0
28     0
29     0
30     0
31    -1
32     1
33     0
34     0
35     0
36    -1

index 31 is replaced to -1 since index 7 is 1. Same as index 36(index 12 is 1). in this case the index 36 value remains.

CodePudding user response:

in your example code, column name is position_short, but in the output it is number. I'll think of it as number. you can change s.

s = df['number']
out = s.where(s.eq(1)).mul(-1).shift(24).fillna(s).astype('int')

out.head(30)

7     1
8    -1
9     0
10    0
11    0
12    1
13    0
14    0
15   -1
16    0
17    0
18    0
19    0
20    0
21    0
22    0
23    0
24    0
25    0
26    0
27    0
28    0
29    0
30    0
31   -1 <--
32    0
33    0
34    0
35    0
36   -1 <--
Name: position_short, dtype: int32
  • Related