【问题标题】:How to make current row value equal to previous row value if a column equals a value in Pandas?如果一列等于 Pandas 中的值,如何使当前行值等于前一行值?
【发布时间】:2020-08-30 10:15:46
【问题描述】:

我有一个如下的数据框:

df

ID  val
1   0.0
2   yes
3   1.0
4   0.0
5   yes

如果列 val 等于“yes”,我如何将以前的值与当前值匹配

我尝试了 df['val'] = df['val'].replace('yes', np.nan).bfill().astype(str) ,但无法正常工作。

想要的输出

ID  val
1   yes
2   yes
3   1.0
4   yes
5   yes

我们可以使用 np.where 和 bfill 吗?这个怎么办?

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    怎么样:

    df.loc[df['val'].shift(-1).eq('yes'), 'val'] = 'yes'
    

    输出:

       ID  val
    0   1  yes
    1   2  yes
    2   3  1.0
    3   4  yes
    4   5  yes
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多