I have a dataframe with 5000 records. I want the null values to be filled with:
平均值(null 之前的所有前一个值,null 之后的第一个后继值)
data:
Date gcs Comp Clay WTS
2020-01-01 1550 41 9.41 22.6
2020-01-02 1540 48 9.50 25.8
2020-01-03 NAN NAN NAN NAN
2020-01-04 1542 42 9.30 23.7
2020-01-05 1580 48 9.10 21.2
2020-01-06 NAN NAN NAN NAN
2020-01-07 1520 40 10 20.2
2020-01-08 1523 30 25 19
例子:
对于日期 2020-01-03,我希望 gcs 列中的空值用 Average(1550,1540,1542) 填充,得到 1544。
1550 和 1540 是 null 之前的前面的值,1542 是 null 之后的第一个后续值。
相似地,
对于日期 2020-01-06,我希望填充 gcs 列的空值
平均值 (1550,1540,1544,1542,1580,1520) 给出 1546。
1550 到 1580 是 null 之前的前一个值,1520 是 null 之后的第一个后续值。
Desired Output:
Date gcs Comp Clay WTS
2020-01-01 1550 41 9.41 22.6
2020-01-02 1540 48 9.50 25.8
2020-01-03 1544 43.66 9.403 24.03
2020-01-04 1542 42 9.30 23.7
2020-01-05 1580 48 9.10 21.2
2020-01-06 1546 43.77 9.45 22.92
2020-01-07 1520 40 10 20.2
2020-01-08 1523 30 25 19
**Edit:
感谢汤姆的回复。
我将日期列保留为索引并尝试了以下代码:
def foo(row):
if any(row.isna()):
df.loc[row.name,row.isna()] = df.expanding().mean().shift(-1).loc[row.name,:]
df.apply(foo, axis=1)
我得到的输出是:
Date
2020-01-01 None
2020-01-02 None
2020-01-03 None
2020-01-04 None
2020-01-05 None
2020-01-06 None
2020-01-07 None
2020-01-08 None
dtype: object
你能帮我找出问题所在吗?