zoukankan      html  css  js  c++  java
  • 做鸢尾花切片练习中的'&'问题:(&,|)和(and,or)

    课上练习:要求取petal_length和petal_width两列,满足筛选条件为sepal_length>=5且species=setosa

    1  iris.loc[(iris['sepal_length']>5)&(iris['species']=='setosa'),['petal_length','petal_width']]

    其中&前后我一开始用的是列表,报错:

    1 ---------------------------------------------------------------------------
    2 TypeError                                 Traceback (most recent call last)
    3 <ipython-input-208-bf5bcdcb2ea9> in <module>
    4 ----> 1 iris.loc[[iris['sepal_length']>5]&[iris['species']=='setosa'],['petal_length','petal_width']]
    5 
    6 TypeError: unsupported operand type(s) for &: 'list' and 'list'

    比较如下:

     1 type(iris['sepal_length']>5) 

    pandas.core.series.Series #返回有索引的序列

     1 type((iris['sepal_length']>5)) 

    pandas.core.series.Series #返回有索引的序列

    1 type([iris['sepal_length']>5]) 

    list                                  #列表 

    原因:得到的是序列,序列因为有索引可以自动对齐,列表没有索引
    (&,|)和(and,or):
    参考:https://blog.csdn.net/weixin_40041218/article/details/80868521
    1>a,b是数值变量, 则&, |表示位运算, and,or则依据是否非0来决定输出
    2>a, b是逻辑变量, 则两类的用法基本一致 

    在DataFrame的切片过程,要注意逻辑变量的使用,需要求得满足多个逻辑条件的数据时,要使用& 和|,在某些条件下用and/ or会报错:

    ‘ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().’

        

  • 相关阅读:
    git 创建一个空分支
    github page的两种类型
    hexo-theme-next
    github网页
    Linux下的CPU使用率与服务器负载的关系与区别
    mysql数据库优化日志(更)-howyue
    图片延时加载
    jQuery实现页面滚动时顶部动态显示隐藏
    TCP与UDP区别
    记一次网站服务器迁移(my)
  • 原文地址:https://www.cnblogs.com/xuwinwin/p/15747379.html
Copyright © 2011-2022 走看看