替换为先前的值

问题描述 投票:-1回答:1

我有一些如上所示的数据帧。该计划的目标是用前一个替换某些特定值。

import pandas as pd
test = pd.DataFrame([2,2,3,1,1,2,4,6,43,23,4,1,3,3,1,1,1,4,5], columns = ['A'])

获得:

enter image description here

如果想要用之前的值替换所有1,可能的解决方案是:

for li in test[test['A'] == 1].index:
    test['A'].iloc[li] = test['A'].iloc[li-1] 

enter image description here

但是,效率非常低。你能建议一个更有效的解决方案吗?

python pandas for-loop
1个回答
1
投票

IIUC,replacenp.nan然后ffill

test.replace(1,np.nan).ffill().astype(int)
Out[881]: 
     A
0    2
1    2
2    3
3    3
4    3
5    2
6    4
7    6
8   43
9   23
10   4
11   4
12   3
13   3
14   3
15   3
16   3
17   4
18   5
© www.soinside.com 2019 - 2024. All rights reserved.