【问题标题】:Forward fill on specific column for specific rows前向填充特定行的特定列
【发布时间】:2022-01-12 04:09:28
【问题描述】:

我有如下数据。每行代表一种特定的颜色,与不同的数字相关联:

Color num1 num2
red 1 2
red 1 na
blue 2 na
blue 2 3
yellow 1 4
yellow 1 na

我想在num2 列上使用前向填充,但只能在相同颜色内使用前向填充。 例如,如果前一行也是blue,则仅用前一行的num2 填充第一行bluenum2

预期结果:

Color num1 num2
red 1 2
red 1 2
blue 2 na
blue 2 3
yellow 1 4
yellow 1 4

我已经尝试了以下代码:

for color in df['color'].unique():
    df[df['color'] == color]['num2']=df[df['color'] == color]['num2'].fillna(method='ffill')

我也尝试过inplace=True,但它不起作用。

【问题讨论】:

    标签: python pandas dataframe nan


    【解决方案1】:

    这是你要找的吗?

    df[['Color']].join(df.groupby('Color').ffill())
    

    【讨论】:

    • 谢谢,只需申请“num2”栏目
    【解决方案2】:
    df = df.replace('na', np.nan)
    df['num2'] = df.groupby('Color')['num2'].ffill()
    

    输出:

    >>> df
        Color  num1 num2
    0     red     1    2
    1     red     1    2
    2    blue     2  NaN
    3    blue     2    3
    4  yellow     1    4
    5  yellow     1    4
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 2018-03-28
      • 2017-01-05
      • 2017-01-04
      相关资源
      最近更新 更多