python pandas.DataFrame.loc函数使用详解


Posted in Python onMarch 26, 2020

官方函数

DataFrame.loc
Access a group of rows and columns by label(s) or a boolean array.
.loc[] is primarily label based, but may also be used with a boolean array.
# 可以使用label值,但是也可以使用布尔值

  • Allowed inputs are: # 可以接受单个的label,多个label的列表,多个label的切片
  • A single label, e.g. 5 or ‘a', (note that 5 is interpreted as a label of the index, and never as an integer position along the index). #这里的5不是数值指定的位置,而是label值
  • A list or array of labels, e.g. [‘a', ‘b', ‘c'].

slice object with labels, e.g. ‘a':'f'.

Warning: #如果使用多个label的切片,那么切片的起始位置都是包含的

Note that contrary to usual python slices, both the start and the stop are included

  • A boolean array of the same length as the axis being sliced, e.g. [True, False, True].

实例详解

一、选择数值

1、生成df

df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
...   index=['cobra', 'viper', 'sidewinder'],
...   columns=['max_speed', 'shield'])

df
Out[15]: 
      max_speed shield
cobra        1    2
viper        4    5
sidewinder     7    8

2、Single label. 单个 row_label 返回的Series

df.loc['viper']
Out[17]: 
max_speed  4
shield    5
Name: viper, dtype: int64

2、List of labels. 列表 row_label 返回的DataFrame

df.loc[['cobra','viper']]
Out[20]: 
    max_speed shield
cobra     1    2
viper     4    5

3、Single label for row and column 同时选定行和列

df.loc['cobra', 'shield']
Out[24]: 2

4、Slice with labels for row and single label for column. As mentioned above, note that both the start and stop of the slice are included. 同时选定多个行和单个列,注意的是通过列表选定多个row label 时,首位均是选定的。

df.loc['cobra':'viper', 'max_speed']
Out[25]: 
cobra  1
viper  4
Name: max_speed, dtype: int64

5、Boolean list with the same length as the row axis 布尔列表选择row label
布尔值列表是根据某个位置的True or False 来选定,如果某个位置的布尔值是True,则选定该row

df
Out[30]: 
      max_speed shield
cobra        1    2
viper        4    5
sidewinder     7    8

df.loc[[True]]
Out[31]: 
    max_speed shield
cobra     1    2

df.loc[[True,False]]
Out[32]: 
    max_speed shield
cobra     1    2

df.loc[[True,False,True]]
Out[33]: 
      max_speed shield
cobra        1    2
sidewinder     7    8

6、Conditional that returns a boolean Series 条件布尔值

df.loc[df['shield'] > 6]
Out[34]: 
      max_speed shield
sidewinder     7    8

7、Conditional that returns a boolean Series with column labels specified 条件布尔值和具体某列的数据

df.loc[df['shield'] > 6, ['max_speed']]
Out[35]: 
      max_speed
sidewinder     7

8、Callable that returns a boolean Series 通过函数得到布尔结果选定数据

df
Out[37]: 
      max_speed shield
cobra        1    2
viper        4    5
sidewinder     7    8

df.loc[lambda df: df['shield'] == 8]
Out[38]: 
      max_speed shield
sidewinder     7    8

二、赋值

1、Set value for all items matching the list of labels 根据某列表选定的row 及某列 column 赋值

df.loc[['viper', 'sidewinder'], ['shield']] = 50

df
Out[43]: 
      max_speed shield
cobra        1    2
viper        4   50
sidewinder     7   50

2、Set value for an entire row 将某行row的数据全部赋值

df.loc['cobra'] =10

df
Out[48]: 
      max_speed shield
cobra       10   10
viper        4   50
sidewinder     7   50

3、Set value for an entire column 将某列的数据完全赋值

df.loc[:, 'max_speed'] = 30

df
Out[50]: 
      max_speed shield
cobra       30   10
viper       30   50
sidewinder     30   50

4、Set value for rows matching callable condition 条件选定rows赋值

df.loc[df['shield'] > 35] = 0

df
Out[52]: 
      max_speed shield
cobra       30   10
viper        0    0
sidewinder     0    0

三、行索引是数值

df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
...   index=[7, 8, 9], columns=['max_speed', 'shield'])

df
Out[54]: 
  max_speed shield
7     1    2
8     4    5
9     7    8

通过 行 rows的切片的方式取多个:

df.loc[7:9]
Out[55]: 
  max_speed shield
7     1    2
8     4    5
9     7    8

四、多维索引

1、生成多维索引

tuples = [
...  ('cobra', 'mark i'), ('cobra', 'mark ii'),
...  ('sidewinder', 'mark i'), ('sidewinder', 'mark ii'),
...  ('viper', 'mark ii'), ('viper', 'mark iii')
... ]
index = pd.MultiIndex.from_tuples(tuples)
values = [[12, 2], [0, 4], [10, 20],
...     [1, 4], [7, 1], [16, 36]]
df = pd.DataFrame(values, columns=['max_speed', 'shield'], index=index)


df
Out[57]: 
           max_speed shield
cobra   mark i      12    2
      mark ii      0    4
sidewinder mark i      10   20
      mark ii      1    4
viper   mark ii      7    1
      mark iii     16   36

2、Single label. 传入的就是最外层的row label,返回DataFrame

df.loc['cobra']
Out[58]: 
     max_speed shield
mark i     12    2
mark ii     0    4

3、Single index tuple.传入的是索引元组,返回Series

df.loc[('cobra', 'mark ii')]
Out[59]: 
max_speed  0
shield    4
Name: (cobra, mark ii), dtype: int64

4、Single label for row and column.如果传入的是row和column,和传入tuple是类似的,返回Series

df.loc['cobra', 'mark i']
Out[60]: 
max_speed  12
shield    2
Name: (cobra, mark i), dtype: int64

5、Single tuple. Note using [[ ]] returns a DataFrame.传入一个数组,返回一个DataFrame

df.loc[[('cobra', 'mark ii')]]
Out[61]: 
        max_speed shield
cobra mark ii     0    4

6、Single tuple for the index with a single label for the column 获取某个colum的某row的数据,需要左边传入多维索引的tuple,然后再传入column

df.loc[('cobra', 'mark i'), 'shield']
Out[62]: 2

7、传入多维索引和单个索引的切片:

df.loc[('cobra', 'mark i'):'viper']
Out[63]: 
           max_speed shield
cobra   mark i      12    2
      mark ii      0    4
sidewinder mark i      10   20
      mark ii      1    4
viper   mark ii      7    1
      mark iii     16   36

df.loc[('cobra', 'mark i'):'sidewinder']
Out[64]: 
          max_speed shield
cobra   mark i     12    2
      mark ii     0    4
sidewinder mark i     10   20
      mark ii     1    4

df.loc[('cobra', 'mark i'):('sidewinder','mark i')]
Out[65]: 
          max_speed shield
cobra   mark i     12    2
      mark ii     0    4
sidewinder mark i     10   20

到此这篇关于python pandas.DataFrame.loc函数使用详解的文章就介绍到这了,更多相关pandas.DataFrame.loc函数内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python开发的单词频率统计工具wordsworth使用方法
Jun 25 Python
Python编码类型转换方法详解
Jul 01 Python
Django查询数据库的性能优化示例代码
Sep 24 Python
详解在Python中以绝对路径或者相对路径导入文件的方法
Aug 30 Python
Pytorch 实现计算分类器准确率(总分类及子分类)
Jan 18 Python
python3读取autocad图形文件.py实例
Jun 05 Python
matplotlib事件处理基础(事件绑定、事件属性)
Feb 03 Python
python基础详解之if循环语句
Apr 24 Python
超详细Python解释器新手安装教程
May 10 Python
Python机器学习之基础概述
May 19 Python
Python通过loop.run_in_executor执行同步代码 同步变为异步
Apr 11 Python
Python开发五子棋小游戏
Apr 28 Python
Python计算指定日期是今年的第几天(三种方法)
Mar 26 #Python
Python函数默认参数常见问题及解决方案
Mar 26 #Python
Python内建序列通用操作6种实现方法
Mar 26 #Python
PyQt5 界面显示无响应的实现
Mar 26 #Python
Python基于class()实现面向对象原理详解
Mar 26 #Python
Python文件读写w+和r+区别解析
Mar 26 #Python
Python装饰器实现方法及应用场景详解
Mar 26 #Python
You might like
php Try Catch异常测试
2009/03/01 PHP
file_get_contents("php://input", "r")实例介绍
2013/07/01 PHP
解析array splice的移除数组中指定键的值,返回一个新的数组
2013/07/02 PHP
php利用cookies实现购物车的方法
2014/12/10 PHP
smarty模板引擎从php中获取数据的方法
2015/01/22 PHP
php+ajax注册实时验证功能
2016/07/20 PHP
js 文件引入实现代码
2010/04/23 Javascript
javascript获得服务器端控件的ID的实现代码
2011/12/28 Javascript
jQuery表格列宽可拖拽改变且兼容firfox
2014/09/03 Javascript
用C/C++来实现 Node.js 的模块(一)
2014/09/24 Javascript
ECMAScript6--解构
2017/03/30 Javascript
Angular.js指令学习中一些重要属性的用法教程
2017/05/24 Javascript
Angular2学习教程之组件中的DOM操作详解
2017/05/28 Javascript
jQuery实现ajax的嵌套请求案例分析
2019/02/16 jQuery
详解将微信小程序接口Promise化并使用async函数
2019/08/05 Javascript
微信小程序 调用远程接口 给全局数组赋值代码实例
2019/08/13 Javascript
JavaScript经典案例之简易计算器
2020/08/24 Javascript
javascript全局自定义鼠标右键菜单
2020/12/08 Javascript
[03:40]DOTA2抗疫特别篇《英雄年代》
2020/02/28 DOTA
在Pandas中DataFrame数据合并,连接(concat,merge,join)的实例
2019/01/29 Python
Python实现的远程文件自动打包并下载功能示例
2019/07/12 Python
Python Selenium自动化获取页面信息的方法
2020/08/31 Python
scrapy头部修改的方法详解
2020/12/06 Python
html5 更新图片颜色示例代码
2014/07/29 HTML / CSS
详解如何使用rem或viewport进行移动端适配
2020/08/14 HTML / CSS
.NET面试10题
2014/02/24 面试题
局域网标准
2016/09/10 面试题
餐饮业会计岗位职责
2013/12/19 职场文书
四风个人对照检查材料思想汇报
2014/09/25 职场文书
2015年先进个人自荐书
2015/03/24 职场文书
幼儿园六一儿童节开幕词
2016/03/04 职场文书
2016年社区党支部公开承诺书
2016/03/25 职场文书
管理者日常工作必备:22条企业管理流程模板!
2019/07/12 职场文书
Python激活Anaconda环境变量的详细步骤
2021/06/08 Python
Element-ui Layout布局(Row和Col组件)的实现
2021/12/06 Vue.js
Go并发4种方法简明讲解
2022/04/06 Golang