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写的贪吃蛇游戏例子
Jun 16 Python
浅析Python中的for 循环
Jun 09 Python
Python利用QQ邮箱发送邮件的实现方法(分享)
Jun 09 Python
机器学习经典算法-logistic回归代码详解
Dec 22 Python
Python实现学生成绩管理系统
Apr 05 Python
pandas把dataframe转成Series,改变列中值的类型方法
Apr 10 Python
Python 访问限制 private public的详细介绍
Oct 16 Python
解决pycharm安装后代码区不能编辑的问题
Oct 28 Python
python右对齐的实例方法
Jul 05 Python
python 实现aes256加密
Nov 27 Python
如何利用python正则表达式匹配版本信息
Dec 09 Python
Python读写yaml文件
Mar 20 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之预定义接口详解
2015/07/29 PHP
php用户名的密码加密更安全的方法
2019/06/21 PHP
PHP $O00OO0=urldecode & eval 解密,记一次商业源码的去后门
2020/09/13 PHP
jQuery基础知识filter()和find()实例说明
2010/07/06 Javascript
js浮点数保留两位小数点示例代码(四舍五入)
2013/12/26 Javascript
JavaScript获得页面base标签中url的方法
2015/04/03 Javascript
js实现不重复导入的方法
2016/03/02 Javascript
JS实现随机颜色的3种方法与颜色格式的转化
2017/01/05 Javascript
详解js中==与===的区别
2017/01/08 Javascript
基于JavaScript实现复选框的全选和取消全选
2017/02/09 Javascript
使用jQuery ajaxupload插件实现无刷新上传文件
2017/04/23 jQuery
bootstrap+jQuery 实现下拉菜单中复选框全选和全不选效果
2017/06/12 jQuery
AngularJS 仿微信图片手势缩放的实例
2017/09/28 Javascript
微信小程序的生命周期的详解
2017/10/19 Javascript
vue项目中添加单元测试的方法
2018/07/21 Javascript
Angular路由ui-router配置详解
2018/08/01 Javascript
React Router V4使用指南(精讲)
2018/09/17 Javascript
JavaScript Array对象基本方法详解
2019/09/03 Javascript
vue实现树形结构样式和功能的实例代码
2019/10/15 Javascript
python对字典进行排序实例
2014/09/25 Python
python实现实时监控文件的方法
2016/08/26 Python
Python八大常见排序算法定义、实现及时间消耗效率分析
2018/04/27 Python
python SQLAlchemy 中的Engine详解
2019/07/04 Python
Python使用itchat 功能分析微信好友性别和位置
2019/08/05 Python
Django连接数据库并实现读写分离过程解析
2019/11/13 Python
解决jupyter运行pyqt代码内核重启的问题
2020/04/16 Python
Python figure参数及subplot子图绘制代码
2020/04/18 Python
Python绘制词云图之可视化神器pyecharts的方法
2021/02/23 Python
HTML5事件方法全部汇总
2016/05/12 HTML / CSS
《晏子使楚》教学反思
2014/02/08 职场文书
交通文明倡议书
2014/05/16 职场文书
法人委托书
2014/07/31 职场文书
2014教师年度工作总结
2014/11/10 职场文书
2014年机关党委工作总结
2014/12/11 职场文书
2016年大学生社会实践心得体会
2015/10/09 职场文书
python基础之文件操作
2021/10/24 Python