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

DataFrame的loc标签,切片,布尔索引选择单行多行多列

老董-我爱我家房产SEO2021-10-25173围观,110赞

  pandas中DataFrame选择数据可以用loc选择器,注意loc不是函数。loc用于标签索引筛选,也可以用于布尔值筛选。

  官方介绍如下:

  Access a group of rows and columns by label(s) or a boolean array。.loc[] is primarily label based, but may also be used with a boolean array.

  我们按照这个df为例来进行学习。


df = pd.DataFrame([['bj','100','200'],['sh','80','60'],['nj','50','30']],columns=['city','sale','rent'],index=['a','b','c'])
print(df)
  city sale rent
a   bj  100  200
b   sh   80   60
c   nj   50   30

  1、loc标签索引选择单行,返回Series或者DataFrame


df = pd.DataFrame([['bj','100','200'],['sh','80','60'],['nj','50','30']],columns=['city','sale','rent'],index=['a','b','c'])
print(df.loc['a'])
print('-------------')
print(df.loc[['a']])
city     bj
sale    100
rent    200
Name: a, dtype: object
-------------
  city sale rent
a   bj  100  200

  2、loc标签索引选择多行及所有列,返回DataFrame


df = pd.DataFrame([['bj','100','200'],['sh','80','60'],['nj','50','30']],columns=['city','sale','rent'],index=['a','b','c'])
print(df.loc[['a','b']])
  city sale rent
a   bj  100  200
b   sh   80   60

  3、loc标签索引选择多行多列,返回DataFrame


df = pd.DataFrame([['bj','100','200'],['sh','80','60'],['nj','50','30']],columns=['city','sale','rent'],index=['a','b','c'])
print(df.loc[['a','b'],['city','sale']])
  city sale
a   bj  100
b   sh   80

  4、loc标签切片索引(末端包含)选择多行及所有列,返回DataFrame


df = pd.DataFrame([['bj','100','200'],['sh','80','60'],['nj','50','30']],columns=['city','sale','rent'],index=['a','b','c'])
print(df.loc['a':'b',:])
print('=====')
print(df.loc[['a','b'],:])
  city sale rent
a   bj  100  200
b   sh   80   60
=====
  city sale rent
a   bj  100  200
b   sh   80   60

  5、loc标签切片索引(末端包含)选择多行多列,返回DataFrame


df = pd.DataFrame([['bj','100','200'],['sh','80','60'],['nj','50','30']],columns=['city','sale','rent'],index=['a','b','c'])
print(df.loc['a':'b','city':'sale'])

  city sale
a   bj  100
b   sh   80

  6、loc布尔索引(末端包含)选择多行多列,返回DataFrame


df = pd.DataFrame([['bj','100','200'],['sh','80','60'],['nj','50','30']],columns=['city','sale','rent'],index=['a','b','c'])
print(df.loc[[True,False,True],'city':'sale'])
print('====')
print(df.loc[[True,False,True],[True,True,False]])
  city sale
a   bj  100
c   nj   50
====
  city sale
a   bj  100
c   nj   50

很赞哦!

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

文章评论

    DataFrame的loc标签,切片,布尔索引选择单行多行多列文章写得不错,值得赞赏

站点信息

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