python教程

当前位置:首页 > Pandas教程 > 当前文章

Pandas教程

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

2021-10-25 107赞 老董笔记

  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

文章评论

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