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

DataFrame直接索引,切片,布尔索引选择单行多行

老董-我爱我家房产SEO2021-10-25191围观,116赞

  pandas中DataFrame直接索引就是df[xx]的形式,可以根据标签索引(index、columns参数)或者位置索引选取数据,也可以进行切片操作。DataFrame是2维数据结构,无论行还是列都存在位置索引,默认都是从0开始。

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

# -*- coding: utf-8 -*-

import pandas as pd

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、列标签索引选择单列,返回Series


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

  2、列标签索引选择单列,返回DataFrame


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

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


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

  4、行标签切片(末端包含)选择多行,返回DataFrame


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

  5、行位置索引切片(末端不包含)选择行,DataFrame


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

  6、行布尔索引选择多行


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

很赞哦!

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

文章评论

    DataFrame直接索引,切片,布尔索引选择单行多行文章写得不错,值得赞赏

站点信息

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