【发布时间】: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 填充第一行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,但它不起作用。
【问题讨论】:
标签: python pandas dataframe nan