-
Series.where(cond, other=nan, inplace=False, axis=None, level=None, errors=‘raise’, try_cast=False, raise_on_error=None)
如果 cond 为真,保持原来的值,否则替换为other, inplace为真标识在原数据上操作,为False标识在原数据的copy上操作。
other must be the same shape as self: other的形状必须与self相同。mask 函数和 where 作用刚好相反。
s = pd.Series(range(5)) s.where(s > 1, 10) 0 10.0 1 10.0 2 2.0 3 3.0 4 4.0 s.mask(s > 1, 10) 0 0.0 1 1.0 2 10.0 3 10.0 4 10.0 df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B']) m = df % 3 == 0 # df.where(m, np.array([1,2,3,4,5]).reshape(-1, 5)) #此句话报错 df.where(m, -df) A B 0 0 -1 1 -2 3 2 -4 -5 3 6 -7 4 -8 9 -
np.ceil 向上取整
The ceil of the scalar x is the smallest integer i, such that i >= x.
函数返回最小的整数i,满足i >= x
a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) np.ceil(a) # array([-1., -1., -0., 1., 2., 2., 2.])
利用以上两个函数将数据集按照地区收入分类:
housing["income_cat"] = np.ceil(housing["median_income"] / 1.5)
housing["income_cat"].where(housing["income_cat"] < 5, 5.0, inplace=True)
本文详细介绍了Pandas库中where与mask函数的使用方法,包括条件判断、替换值等核心功能。通过实例展示了如何在Series和DataFrame上应用这些函数,并解释了np.ceil函数的用途,最后给出了一个数据集按地区收入分类的实际案例。
926

被折叠的 条评论
为什么被折叠?



