【问题标题】:Replace the below n rows values of a specific column with the same value将特定列的以下 n 行值替换为相同的值
【发布时间】:2020-03-31 20:05:38
【问题描述】:

我有一个这样的数据框,

df
col1    col2
 1       D
 2       A
 3       H
 4       K
 5       G
 6       A
 7       K
 8       H
 9       B
10       S

现在如果 col2 值是 A 然后用 A 填充接下来的两行(我们可以更改数字) 所以结果看起来像,

df
col1    col2
 1       D
 2       A
 3       A
 4       A
 5       G
 6       A
 7       A
 8       A
 9       B
10       S

我可以使用 for 循环来做到这一点,并将一个与另一个进行比较。但执行时间会更长。所以我正在寻找一些 pandas 快捷方式/pythonic 方式来有效地做到这一点。

【问题讨论】:

  • 将记录在案的位置设施(索引)与“行切片”一起使用。

标签: python pandas dataframe


【解决方案1】:

Series.whereSeries.ffilllimit=2 一起使用。最后我们使用Series.fillna 补全非A且不在限定范围内的值。

df['col2'] = df['col2'].where(df['col2'].eq('A')).ffill(limit=2).fillna(df['col2'])

输出

   col1 col2 new_col2
0     1    D        D
1     2    A        A
2     3    H        A
3     4    K        A
4     5    G        G
5     6    A        A
6     7    K        A
7     8    H        A
8     9    B        B
9    10    S        S

我们也可以使用DataFrame.rolling

df.loc[df['col2'].eq('A').rolling(3, min_periods=0).max().astype(bool),'col2'] = 'A'

【讨论】:

    【解决方案2】:

    您可以尝试将ffilllimit=2fillna 一起使用

    df['new_col2'] = df.col2.where(df.col2.eq('A')).ffill(limit=2).fillna(df.col2)
    
    Out[164]:
       col1 col2 new_col2
    0     1    D        D
    1     2    A        A
    2     3    H        A
    3     4    K        A
    4     5    G        G
    5     6    A        A
    6     7    K        A
    7     8    H        A
    8     9    B        B
    9    10    S        S
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-13
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      • 2017-04-28
      • 1970-01-01
      • 2017-08-11
      相关资源
      最近更新 更多