您的位置: 网站首页> Pandas教程> 当前文章

DataFrame的[],loc,iloc多条件判断筛选(布尔索引的本质)

老董-我爱我家房产SEO2021-10-25179围观,113赞

  pandas中DataFrame选择数据可以用直接索引、loc选择器、iloc选择器,这些筛选方式都支持布尔索引,他们可以直接传入True、False组成的列表,也可以传入Series、df、np数组,只要他们的值为布尔值即可。这个就是布尔索引的本质。详细用法如下:

  >>dateframe loc行列选择,切片,条件筛选大全

  >>dateframe iloc行列选择,切片,条件筛选大全

  >>dateframe []直接索引,切片,条件筛选大全

  在多条件判断中,&代表且,|代表或,~代表取反。如果2个条件运算需要加上小括号确定优先级。布尔索引是实际工作使用非常频繁的操作,本文实操利用布尔索引进行单条件多条件判断。

  1、单条件与非判断


df = pd.DataFrame([['baidu',800,200],['sogou',500,150],['google',100,60]],columns=['pingtai','pv','uv'],index=['a','b','c'])
bool_con1 = df['pv'] > 200
print(df[bool_con1])
print('====')
print(df[~bool_con1]) # 取反
  pingtai   pv   uv
a   baidu  800  200
b   sogou  500  150
====
  pingtai   pv  uv
c  google  100  60

  2、多条件与判断


df = pd.DataFrame([['baidu',800,200],['sogou',600,100],['google',500,120]],columns=['pingtai','pv','uv'],index=['a','b','c'])
bool_con1 = df['pv'] > 500
print(df[bool_con1])
print('====')
bool_con2 = df['uv'] > 100
print(df[bool_con2])
print('-----')
print(df[bool_con2 & bool_con1])
  pingtai   pv   uv
a   baidu  800  200
b   sogou  600  100
====
  pingtai   pv   uv
a   baidu  800  200
c  google  500  120
-----
  pingtai   pv   uv
a   baidu  800  200

  3、多条件或判断


df = pd.DataFrame([['baidu',800,200],['sogou',600,100],['google',500,120]],columns=['pingtai','pv','uv'],index=['a','b','c'])
bool_con1 = df['pv'] > 500
print(df[bool_con1])
print('====')
bool_con2 = df['uv'] > 100
print(df[bool_con2])
print('-----')
print(df[bool_con2 | bool_con1])
  pingtai   pv   uv
a   baidu  800  200
b   sogou  600  100
====
  pingtai   pv   uv
a   baidu  800  200
c  google  500  120
-----
  pingtai   pv   uv
a   baidu  800  200
b   sogou  600  100
c  google  500  120

  4、条件很多可以加括号确定优先级

df = pd.DataFrame([['baidu',800,200],['sogou',600,100],['google',500,120]],columns=['pingtai','pv','uv'],index=['a','b','c'])
bool_con1 = df['pv'] > 500
print(df[bool_con1])
print('====')
bool_con2 = df['uv'] > 100
print(df[bool_con2])
print('=====')
bool_con3 = df['pingtai'] == 'baidu'
print(df[bool_con3])
print('-----')
print(df[(bool_con2 | bool_con1) & bool_con3])
  pingtai   pv   uv
a   baidu  800  200
b   sogou  600  100
====
  pingtai   pv   uv
a   baidu  800  200
c  google  500  120
=====
  pingtai   pv   uv
a   baidu  800  200
-----
  pingtai   pv   uv
a   baidu  800  200

很赞哦!

python编程网提示:转载请注明来源www.python66.com。
有宝贵意见可添加站长微信(底部),获取技术资料请到公众号(底部)。同行交流请加群 python学习会

文章评论

    DataFrame的[],loc,iloc多条件判断筛选(布尔索引的本质)文章写得不错,值得赞赏

站点信息

  • 网站程序:Laravel
  • 客服微信:a772483200