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().’

        

  • 相关阅读:
    SQL后台分页三种方案和分析
    SQL分页查询语句
    SQL利用临时表实现动态列、动态添加列
    查询sybase DB中占用空间最多的前20张表
    敏捷软件开发之TDD(一)
    敏捷软件开发之开篇
    Sql Server 2012启动存储过程
    改变VS2013的菜单栏字母为小写
    Sql Server获得每个表的行数
    Sql Server trace flags
  • 原文地址:https://www.cnblogs.com/xuwinwin/p/15747379.html
Copyright © 2011-2022 走看看