首页 > 解决方案 > 如果当前行中某列的值为1,则将当前行替换为上一行的数据

问题描述

我有一个 pandas 数据框,如果当前行中某列的值为 1,则想用前一行的数据替换当前行,但还没有成功。任何帮助表示赞赏。

标签: pythonpandasdataframe

解决方案


可以这样做:

#B is the column that lets you know if the row should change or not
for i in range(1, len(df)):
    if df.loc[i, 'B'] == 1:
        df.loc[i, :] = df.loc[i-1, :]

推荐阅读