对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设计】。

相关文章

wxPython实现绘图小例子

wxPython实现绘图小例子

本文实例为大家分享了wxPython绘图小例子的具体实现代码,供大家参考,具体内容如下 一个绘图的例子: #!/usr/bin/env python # -*- coding: ut...

可能是最全面的 Python 字符串拼接总结【收藏】

在 Python 中字符串连接有多种方式,这里简单做个总结,应该是比较全面的了,方便以后查阅。 加号连接 第一种,通过+号的形式: >>> a, b = 'hel...

Python守护进程(daemon)代码实例

# -*-coding:utf-8-*- import sys, os '''将当前进程fork为一个守护进程 注意:如果你的守护进程是由inetd启动的,不要这样做!ine...

Python之re操作方法(详解)

一:re.search():search返回的是查找结果的对象,可以使用group()或groups()方法得到匹配成功的字符串。 ①group() 默认返回匹配成功的整个字符串(忽略p...

python生成tensorflow输入输出的图像格式的方法

TensorFLow能够识别的图像文件,可以通过numpy,使用tf.Variable或者tf.placeholder加载进tensorflow;也可以通过自带函数(tf.read)读取...