pandas where函数用法

  • 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)
  • 4
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值