pandas 按特定顺序替换行(panda Dataframe )

pod7payv  于 2022-12-21  发布在  其他
关注(0)|答案(1)|浏览(130)

我尝试在条件下替换特定行的值
以下是示例 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的值保持不变。

envsm3lx

envsm3lx1#

在你的示例代码中,列名是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

相关问题