Python 替换为以前的值

Python 替换为以前的值,python,pandas,for-loop,Python,Pandas,For Loop,我有一些数据帧,如上图所示。该程序的目标是用前一个值替换某些特定值 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']) 获得: 如果要用以前的值替换所有1,可能的解决方案是: for li in test[test['A'] == 1].index: test['A'].iloc[li] = test['A'].iloc[li-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'])
获得:

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

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


然而,这是非常低效的。你能推荐一个更有效的解决方案吗?

IIUC,
替换
np.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

如果你仔细看,我留下的是代码,而不是代码的图像。我贴了一张输出的图片,这是完全不同的。我确实仔细看了,虽然它在学究方面不一样,但它属于同一类别,有相同的问题。我应该能够复制粘贴这些输入直接到我的编辑器,以帮助您解决这个问题。当你强迫我们转录图像时,你浪费了每个人的时间。你读过问题了吗?