前向填充特定行的特定列
Forward fill on specific column for specific rows
我有如下数据。每行对应一种特定的颜色,与不同的数字相关联:
Color
num1
num2
red
1
2
red
1
na
blue
2
na
blue
2
3
yellow
1
4
yellow
1
na
我想在 num2
列上使用正向填充,但只能使用相同颜色的正向填充。
例如,如果前一行也是 blue
.
,则只用前一行的 num2
填充第一个 blue
行的 num2
预期结果:
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
但它不起作用。
这是您要找的吗?
df[['Color']].join(df.groupby('Color').ffill())
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
我有如下数据。每行对应一种特定的颜色,与不同的数字相关联:
Color | num1 | num2 |
---|---|---|
red | 1 | 2 |
red | 1 | na |
blue | 2 | na |
blue | 2 | 3 |
yellow | 1 | 4 |
yellow | 1 | na |
我想在 num2
列上使用正向填充,但只能使用相同颜色的正向填充。
例如,如果前一行也是 blue
.
num2
填充第一个 blue
行的 num2
预期结果:
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
但它不起作用。
这是您要找的吗?
df[['Color']].join(df.groupby('Color').ffill())
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