我尝试在条件下替换特定行的值
以下是示例 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)
它看起来像这样:
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替换值1的+24行中的每个值。
以下是所需的输出:
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的值保持不变。
1条答案
按热度按时间envsm3lx1#
在你的示例代码中,列名是
position_short
,但是在输出中它是number
。我将把它看作number
。你可以改变s
。外封头(30)