import pandas as pd
from pandas import Series, DataFrame
import numpy as np
a = pd.Series([np.nan, 2.5, 0.0, 3.5, 4.5, np.nan],
index = ['f', 'e', 'd', 'c', 'b', 'a'])
b = pd.Series([0, np.nan, 2., np.nan, np.nan, 5.],
index = ['a', 'b', 'c', 'd', 'e', 'f'])
a
Out[11]:
f NaN
e 2.5
d 0.0
c 3.5
b 4.5
a NaN
dtype: float64
b
Out[12]:
a 0.0
b NaN
c 2.0
d NaN
e NaN
f 5.0
dtype: float64
np.where(pd.isnull(a), b, a)
Out[13]: array([0. , 2.5, 0. , 3.5, 4.5, 5. ])
np.where(pd.isnull(b), b, a)
Out[14]: array([nan, nan, 0., nan, nan, nan])
谁帮忙解释一下np.where(pd.isnull(a), b, a) 和 np.where(pd.isnull(b), b, a) 是什么意思啊?谢谢。
np.where(pd.isnull(a), b, a) 就是把a里面是空的用b对应的值替换,不然还是用a的值
# import numpy as np # import pandas as pd # np.where(condition,x,y) # 函数是三元表达式 x if condition else y 的矢量化版本 # isnull 判断某列数据是否有空值 # np.where(pd.isnull(a), b, a) # 返回数组, 若数组a中isnull的位置 # 用b中的元素填充,其他用a中元素填充 # np.where(pd.isnull(b), b, a) 同理
1