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

相关文章

python 地图经纬度转换、纠偏的实例代码

python 地图经纬度转换、纠偏的代码如下所示: # -*- coding: utf-8 -*- import json import urllib import math x_p...

Python中查看文件名和文件路径

查看文件名和文件路径 >>> import os >>> url = 'http://images.cnitblog.com/i/311516/2...

Python实现的朴素贝叶斯算法经典示例【测试可用】

本文实例讲述了Python实现的朴素贝叶斯算法。分享给大家供大家参考,具体如下: 代码主要参考机器学习实战那本书,发现最近老外的书确实比中国人写的好,由浅入深,代码通俗易懂,不多说上代码...

python实现串口自动触发工作的示例

最近在一个python工具中需要实现串口自动触发工作的功能,之前只在winform上面实现,今天使用python试试。这里简单记一下: 首先用wxpython实现一个Button,点击事...

Python BeautifulSoup [解决方法] TypeError: list indices must be integers or slices, not str

在python的Beautiful Soup 4 扩展库的使用过程中出现了 TypeError: list indices must be integers or slices, no...