pandas索引操作
Pandas的索引操作
索引对象Index
1. Series和DataFrame中的索引都是Index对象
示例代码:
print(type(ser_obj.index))
print(type(df_obj2.index)) print(df_obj2.index)
运行结果:
<class 'pandas.indexes.range.RangeIndex'>
<class 'pandas.indexes.numeric.Int64Index'>
Int64Index([0, 1, 2, 3], dtype='int64')
2. 索引对象不可变,保证了数据的安全
示例代码:
# 索引对象不可变
df_obj2.index[0] = 2
运行结果:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-23-7f40a356d7d1> in <module>()
1 # 索引对象不可变
----> 2 df_obj2.index[0] = 2 /Users/Power/anaconda/lib/python3.6/site-packages/pandas/indexes/base.py in __setitem__(self, key, value)
1402
1403 def __setitem__(self, key, value):
-> 1404 raise TypeError("Index does not support mutable operations")
1405
1406 def __getitem__(self, key): TypeError: Index does not support mutable operations
常见的Index种类
- Index,索引
- Int64Index,整数索引
- MultiIndex,层级索引
- DatetimeIndex,时间戳类型
Series索引
1. index 指定行索引名
示例代码:
ser_obj = pd.Series(range(5), index = ['a', 'b', 'c', 'd', 'e'])
print(ser_obj.head())
运行结果:
a 0
b 1
c 2
d 3
e 4
dtype: int64
2. 行索引
ser_obj[‘label’], ser_obj[pos]
示例代码:
# 行索引
print(ser_obj['b'])
print(ser_obj[2])
运行结果:
1
2
3. 切片索引
ser_obj[2:4], ser_obj[‘label1’: ’label3’]
注意,按索引名切片操作时,是包含终止索引的。
示例代码:
# 切片索引
print(ser_obj[1:3])
print(ser_obj['b':'d'])
运行结果:
b 1
c 2
dtype: int64
b 1
c 2
d 3
dtype: int64
4. 不连续索引
ser_obj[[‘label1’, ’label2’, ‘label3’]]
示例代码:
# 不连续索引
print(ser_obj[[0, 2, 4]])
print(ser_obj[['a', 'e']])
运行结果:
a 0
c 2
e 4
dtype: int64
a 0
e 4
dtype: int64
5. 布尔索引
示例代码:
# 布尔索引
ser_bool = ser_obj > 2
print(ser_bool)
print(ser_obj[ser_bool]) print(ser_obj[ser_obj > 2])
运行结果:
a False
b False
c False
d True
e True
dtype: bool
d 3
e 4
dtype: int64
d 3
e 4
dtype: int64
DataFrame索引
1. columns 指定列索引名
示例代码:
import numpy as np df_obj = pd.DataFrame(np.random.randn(5,4), columns = ['a', 'b', 'c', 'd'])
print(df_obj.head())
运行结果:
a b c d
0 -0.241678 0.621589 0.843546 -0.383105
1 -0.526918 -0.485325 1.124420 -0.653144
2 -1.074163 0.939324 -0.309822 -0.209149
3 -0.716816 1.844654 -2.123637 -1.323484
4 0.368212 -0.910324 0.064703 0.486016

2. 列索引
df_obj[[‘label’]]
示例代码:
# 列索引
print(df_obj['a']) # 返回Series类型
print(df_obj[[0]]) # 返回DataFrame类型
print(type(df_obj[[0]])) # 返回DataFrame类型
运行结果:
0 -0.241678
1 -0.526918
2 -1.074163
3 -0.716816
4 0.368212
Name: a, dtype: float64
<class 'pandas.core.frame.DataFrame'>
3. 不连续索引
df_obj[[‘label1’, ‘label2’]]
示例代码:
# 不连续索引
print(df_obj[['a','c']])
print(df_obj[[1, 3]])
运行结果:
a c
0 -0.241678 0.843546
1 -0.526918 1.124420
2 -1.074163 -0.309822
3 -0.716816 -2.123637
4 0.368212 0.064703
b d
0 0.621589 -0.383105
1 -0.485325 -0.653144
2 0.939324 -0.209149
3 1.844654 -1.323484
4 -0.910324 0.486016
高级索引:标签、位置和混合
Pandas的高级索引有3种
1. loc 标签索引
DataFrame 不能直接切片,可以通过loc来做切片
loc是基于标签名的索引,也就是我们自定义的索引名
示例代码:
# 标签索引 loc
# Series
print(ser_obj['b':'d'])
print(ser_obj.loc['b':'d']) # DataFrame
print(df_obj['a']) # 第一个参数索引行,第二个参数是列
print(df_obj.loc[0:2, 'a'])
运行结果:
b 1
c 2
d 3
dtype: int64
b 1
c 2
d 3
dtype: int64 0 -0.241678
1 -0.526918
2 -1.074163
3 -0.716816
4 0.368212
Name: a, dtype: float64
0 -0.241678
1 -0.526918
2 -1.074163
Name: a, dtype: float64
2. iloc 位置索引
作用和loc一样,不过是基于索引编号来索引
示例代码:
# 整型位置索引 iloc
# Series
print(ser_obj[1:3])
print(ser_obj.iloc[1:3]) # DataFrame
print(df_obj.iloc[0:2, 0]) # 注意和df_obj.loc[0:2, 'a']的区别
运行结果:
b 1
c 2
dtype: int64
b 1
c 2
dtype: int64 0 -0.241678
1 -0.526918
Name: a, dtype: float64
3. ix 标签与位置混合索引
ix是以上二者的综合,既可以使用索引编号,又可以使用自定义索引,要视情况不同来使用,
如果索引既有数字又有英文,那么这种方式是不建议使用的,容易导致定位的混乱。
示例代码:
# 混合索引 ix
# Series
print(ser_obj.ix[1:3])
print(ser_obj.ix['b':'c']) # DataFrame
print(df_obj.loc[0:2, 'a'])
print(df_obj.ix[0:2, 0])
运行结果:
b 1
c 2
dtype: int64
b 1
c 2
dtype: int64 0 -0.241678
1 -0.526918
2 -1.074163
Name: a, dtype: float64
注意
DataFrame索引操作,可将其看作ndarray的索引操作
标签的切片索引是包含末尾位置的
pandas索引操作的更多相关文章
- 【python】pandas 索引操作
选择.修改数据(单层索引) 推荐使用.at..iat..loc..iloc 操作 句法 结果 备注 选择列 df[col] Series 基于列名(列的标签),返回Series 用标签选择行 df.l ...
- 数据分析06 /pandas高级操作相关案例:人口案例分析、2012美国大选献金项目数据分析
数据分析06 /pandas高级操作相关案例:人口案例分析.2012美国大选献金项目数据分析 目录 数据分析06 /pandas高级操作相关案例:人口案例分析.2012美国大选献金项目数据分析 1. ...
- pandas神器操作excel表格大全(数据分析数据预处理)
使用pandas库操作excel,csv表格操作大全 关注公众号"轻松学编程"了解更多,文末有公众号二维码,可以扫码关注哦. 前言 准备三份csv表格做演示: 成绩表.csv su ...
- pandas高级操作
pandas高级操作 import numpy as np import pandas as pd from pandas import DataFrame,Series 替换操作 替换操作可以同步作 ...
- 【Python自动化Excel】Python与pandas字符串操作
Python之所以能够成为流行的数据分析语言,有一部分原因在于其简洁易用的字符串处理能力. Python的字符串对象封装了很多开箱即用的内置方法,处理单个字符串时十分方便:对于Excel.csv等表格 ...
- Mongodb学习笔记三(Mongodb索引操作及性能测试)
第三章 索引操作及性能测试 索引在大数据下的重要性就不多说了 下面测试中用到了mongodb的一个客户端工具Robomongo,大家可以在网上选择下载.官网下载地址:http://www.robomo ...
- Elasticsearch-PHP 索引操作(转)
索引操作 本节通过客户端来介绍一下索引API的各种操作.索引操作包含任何管理索引本身(例如,创建索引,删除索引,更改映射等等). 我们通过一些常见的操作的代码片段来介绍,然后在表格中列出剩下的方法.R ...
- ElasticSearch+Kibana 索引操作
ElasticSearch+Kibana 索引操作 一 前言 ElasticiSearch 简介 ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引 ...
- Mysql之表的操作与索引操作
表的操作: 1.表的创建: create table if not exists table_name(字段定义); 例子: create table if not exists user(id in ...
随机推荐
- Forms and Reports Developer 10g Certified on Windows 10 for EBS 12.x
Forms Developer 10g and Reports Developer 10g are now certified on Windows 10 desktops for E-Busines ...
- 【Python】函数对象
转:作者:Vamei 出处:http://www.cnblogs.com/vamei 函数也是一个对象,具有属性(可以使用dir()查询).作为对象,它还可以赋值给其它对象名,或者作为参数传递. la ...
- centos 使用yum安装MySQL 5.7
想在centos上安装一个MySQL,使用yum install mysql-server 安装提示仓库没有包,也是醉了. 找了很多博客,发现一个很好用的,推荐给大家. 地址:https://blog ...
- VMware安装VMwareTolls
要先启动Ubuntu,用root用户进入. 然后点击VMware的虚拟机——设置——安装VMwareTools 桌面会有一个安装包,解压后,执行vmware-install.pl 安装需要等别以为是安 ...
- AFNetworking网络请求与图片上传工具(POST)
AFNetworking网络请求与图片上传工具(POST) .h文件 #import <Foundation/Foundation.h> /** 成功Block */ typedef vo ...
- oracle 存储过程心得2
1.退出存储过程 return if old_save_time = new_save_time then--没有最新数据,退出 insert into hy_data_handle_mark(id, ...
- Compile For Cydia Submission Author: BigBoss Updated September 23, 2011
Compile For Cydia Submission Author: BigBoss Updated September 23, 2011: In order to submit your app ...
- LeetCode Valid Parenthesis String
原题链接在这里:https://leetcode.com/problems/valid-parenthesis-string/description/ 题目: Given a string conta ...
- datetimefield和datefield的区别
django创建关于时间的model时,有三个可选,datetimefield.datefield和timefield,这三个分别对应datetime.date.time对象,这三个对象都有共同的属性 ...
- Hadoop体系结构之 Mapreduce
MR框架是由一个单独运行在主节点上的JobTracker和运行在每个集群从节点上的TaskTracker共同组成.主节点负责调度构成一个作业的所有任务,这些任务分布在不同的不同的从节点上.主节点监视它 ...