对pandas中iloc,loc取数据差别及按条件取值的方法详解

yipeiwu_com5年前Python基础

Dataframe使用loc取某几行几列的数据:

print(df.loc[0:4,['item_price_level','item_sales_level','item_collected_level','item_pv_level']])

结果如下,取了index为0到4的五行四列数据。

  item_price_level item_sales_level item_collected_level item_pv_level
0     3     3      4    14
1     3     3      4    14
2     3     3      4    14
3     3     3      4    14
4     3     3      4    14

而使用iloc,如下所示:

print(df.iloc[0:4,6:9])

结果如下,取得是index为0到3四行,以及第6到8列(从0列开始)3列数据。

  item_price_level item_sales_level item_collected_level
0     3     3      4
1     3     3      4
2     3     3      4
3     3     3      4

另外loc可以按条件取数据:

print(df.loc[df.item_price_level==0,:])
print(df.loc[df[item_price_level]==0,:])

上面两条语句效果是一样的,都是取item_price_level为0的所有数据。可以把冒号改成几列列名,只取满足条件的某几列数据:

print(df.loc[df['item_price_level']==0,['item_price_level','item_sales_level']])

结果前两行如下:

   item_price_level item_sales_level
129141     0    10
129142     0    10

条件为多个时 (同时满足两个条件如下):

print(df.loc[(item_price_level==0) & (item_sales_level==3),:])
 

以上这篇对pandas中iloc,loc取数据差别及按条件取值的方法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Scrapy框架使用的基本知识

scrapy是一个基于Twisted的异步处理框架,可扩展性很强。优点此处不再一一赘述。 下面介绍一些概念性知识,帮助大家理解scrapy。 一、数据流向 要想熟练掌握这个框架,一定要明...

关于pymysql模块的使用以及代码详解

pymysql模块的使用 查询一条数据fetchone() from pymysql import * conn = connect( host='127.0.0.1',...

Python3 queue队列模块详细介绍

queue介绍 queue是python中的标准库,俗称队列。 在python中,多个线程之间的数据是共享的,多个线程进行数据交换的时候,不能够保证数据的安全性和一致性,所以当多个线程需...

Python3实现连接SQLite数据库的方法

本文实例讲述了Python3实现连接SQLite数据库的方法,对于Python的学习有不错的参考借鉴价值。分享给大家供大家参考之用。具体方法如下: 实例代码如下: import sq...

对Python 语音识别框架详解

如下所示: from win32com.client import constants import os import win32com.client import pythonc...