我试图在条件下替换特定行的值
以下是示例数据帧:
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)
它看起来像这样:
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
我试图用-1替换位于+24行值1中的每个值。
以下是所需的输出:
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
索引31被替换为-1,因为索引7是1。与索引36相同(索引12为1)。在这种情况下,索引36的值保持不变。
在示例代码中,列名为position_short
,但在输出中为number
。我认为它是number
。您可以更改s
。
s = df['number']
out = s.where(s.eq(1)).mul(-1).shift(24).fillna(s).astype('int')
出料头(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