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

yipeiwu_com6年前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设计】。

相关文章

对python For 循环的三种遍历方式解析

实例如下所示: array = ["a","b","c"] for item in array: print(item) for index in range(len...

Django在admin后台集成TinyMCE富文本编辑器的例子

Django在admin后台集成TinyMCE富文本编辑器的例子

Django原生的TextField并不友好,集成TinyMCE富文本编辑器 Django版本:1.11.5 TinyMCE版本:4.6.7 第一步:从官网下载TinyMCE https...

Python数据处理篇之Sympy系列(五)---解方程

Python数据处理篇之Sympy系列(五)---解方程

前言 sympy不仅在符号运算方面强大,在解方程方面也是很强大。 本章节学习对应官网的:Solvers 官方教程 https://docs.sympy.org/latest/tutor...

python文件操作之批量修改文件后缀名的方法

1、引言 需要把.dat 格式 转化成 .txt格式 2、实现 ##python批量更换后缀名 import os # 列出当前目录下所有的文件 files = os.listdir...

python3实现指定目录下文件sha256及文件大小统计

python3实现指定目录下文件sha256及文件大小统计

有时会统计某个目录下有哪些文件,每个文件的sha256及文件大小等相关信息,这里用python3写了个脚本用来实现此功能,此脚本可跨平台,同时支持windows和linux,脚本(get...