如何根据另一列中的值填充一行中的空值。
A B
0 5
1 NAN
1 6
0 NAN
对于 B 中的 null 值,如果 A 中的对应值为 0,则填充上一个值。
A B
0 5
1 NAN
1 6
0 6
```
it want it to be like this
numpy.where+ isnull+ffill
df.assign(
B=np.where(df.A.eq(0) & df.B.isnull(), df.B.ffill(), df.B)
)
A B
0 0 5.0
1 1 NaN
2 1 6.0
3 0 6.0
一种更快的方法(与以前的方法相比):
import pandas as pd
import numpy as np
df = pd.DataFrame({'A':[0,1,1,0], 'B':[5,np.nan,6,np.nan]})
df.B = np.where(df.A==0, df.B.ffill(), df.B)
你得到:
A B
0 0 5.0
1 1 NaN
2 1 6.0
3 0 6.0
另一种使用 loc 的方法,
df.loc[df['A'].eq(0), 'B'] = df['B'].ffill()
A B
0 0 5
1 1 NaN
2 1 6
3 0 6