pandas值向下填充
时间: 2024-03-31 09:31:05 浏览: 74
以下是两种pandas值向下填充的方法:
1. 使用`fillna`函数和`method='ffill'`参数[^2]:
```python
import pandas as pd
# 创建一个示例DataFrame
data = {'A': [1, None, None, 4],
'B': [None, 2, None, None],
'C': [3, None, 6, None]}
df = pd.DataFrame(data)
# 在指定列中向下填充值
df['A'].fillna(method='ffill', inplace=True)
df['B'].fillna(method='ffill', inplace=True)
df['C'].fillna(method='ffill', inplace=True)
print(df)
```
输出:
```
A B C
0 1.0 NaN 3.0
1 1.0 2.0 3.0
2 1.0 2.0 6.0
3 4.0 2.0 6.0
```
2. 使用`backfill`或`bfill`方法[^1]:
```python
import pandas as pd
import numpy as np
df = pd.DataFrame([[np.nan, 2, np.nan, 0],
[3, 4, np.nan, 1],
[np.nan, np.nan, np.nan, 5],
[np.nan, 3, np.nan, 4]], columns=list('ABCD'))
# 使用backfill/bfill方法向下填充缺失值
df.fillna(method='backfill', inplace=True)
print(df)
```
输出:
```
A B C D
0 3.0 2.0 NaN 0
1 3.0 4.0 NaN 1
2 NaN 3.0 NaN 5
3 NaN 3.0 NaN 4
```
阅读全文