Pandas的标签处理需要分成多种情况来处理,Series和DataFrame根据标签索引数据的操作方法是不同的,单列索引和双列索引的操作方法也是不同的。

单列索引

In [2]: import pandas as pd

In [3]: import numpy as np

In [4]: df = pd.DataFrame(np.ones((2, 4)), index=list("AB"), columns=list("abcd"))

In [5]: df.iloc[0,0]=100

In [6]: df
Out[6]:
a b c d
A 100.0 1.0 1.0 1.0
B 1.0 1.0 1.0 1.0

reindex所插入的标签如果是原来的标签中没有的,就会将该行的值全部置为NaN

In [7]: df.reindex(["A", "f"])
Out[7]: ssss
a b c d
A 100.0 1.0 1.0 1.0
f NaN NaN NaN NaN In [8]: df
Out[8]:
a b c d
A 100.0 1.0 1.0 1.0
B 1.0 1.0 1.0 1.0

使用index修改标签

In [9]: df.index = ["a", "b"]

In [10]: df
Out[10]:
a b c d
a 100.0 1.0 1.0 1.0
b 1.0 1.0 1.0 1.0

使用set_index将某一列变为标签

In [11]: df.set_index("a")
Out[11]:
​ b c d
a
100.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 In [12]: df
Out[12]:
​ a b c d
a 100.0 1.0 1.0 1.0
b 1.0 1.0 1.0 1.0
# 使用drop参数控制将某一列作为索引后是否删除原数据
In [13]: df.set_index("a", drop=False)
Out[13]:
​ a b c d
a
100.0 100.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
# 使用unique函数可以去除重复值
In [14]: df.set_index("b", drop=False).index.unique()
Out[14]: Float64Index([1.0], dtype='float64', name='b') In [15]: df.set_index("b", drop=False).index
Out[15]: Float64Index([1.0, 1.0], dtype='float64', name='b') In [16]: len(df.set_index("b", drop=False).index.unique())
Out[16]: 1

双列索引

In [17]: df.set_index(["a","b"])
Out[17]:
c d
a b
100.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
# levels这个列表中含有两个列表,分别是双列索引的每一列
In [18]: df.set_index(["a","b"]).index
Out[18]:
MultiIndex(levels=[[1.0, 100.0], [1.0]],
labels=[[1, 0], [0, 0]],
names=['a', 'b']) In [19]: a = pd.DataFrame({'a': range(7),'b': range(7, 0, -1),'c': ['one','one','one','two','two','two', 'two'],'d': list("hjklmno")}) In [20]: a
Out[20]:
a b c d
0 0 7 one h
1 1 6 one j
2 2 5 one k
3 3 4 two l
4 4 3 two m
5 5 2 two n
6 6 1 two o In [21]: b = a.set_index(["c","d"]) In [22]: b
Out[22]:
​ a b
c d
one h 0 7
​ j 1 6
​ k 2 5
two l 3 4
​ m 4 3
​ n 5 2
​ o 6 1 In [23]: c = b["a"] In [24]: c
Out[24]:
c d
one h 0
​ j 1
​ k 2
two l 3
​ m 4
​ n 5
​ o 6
Name: a, dtype: int64

双列索引取值

In [25]: c["two"]["l"]
Out[25]: 3 In [26]: c["one"]
Out[26]:
d
h 0
j 1
k 2
Name: a, dtype: int64 In [27]: d = a.set_index(["d","c"]) In [28]: d = d["a"] In [43]: d
Out[43]:
d c
h one 0
j one 1
k one 2
l two 3
m two 4
n two 5
o two 6
Name: a, dtype: int64
# 对于索引数少的列在后的情况,如果直接取会发生错误
In [44]: d["one"]
---------------------------------------------------------------------------
KeyError Traceback (most recent call
...
KeyError: 'one'

swaplevel()函数进行标签列换位

In [45]: d.swaplevel()
Out[45]:
c d
one h 0
​ j 1
​ k 2
two l 3
​ m 4
​ n 5
​ o 6
Name: a, dtype: int64 In [46]: d = d.swaplevel() In [47]: d["one"]
Out[47]:
d
h 0
j 1
k 2
Name: a, dtype: int64 In [48]: b
Out[48]:
​ a b
c d
one h 0 7
​ j 1 6
​ k 2 5
two l 3 4
​ m 4 3
​ n 5 2
​ o 6 1

对于DataFrame类型数组的双列索引,取值时应该加上loc或iloc

In [49]: b.loc["one"]
Out[49]:
a b
d
h 0 7
j 1 6
k 2 5 In [51]: d.loc["two"].loc["m"]
Out[51]: 4

Pandas之索引的更多相关文章

  1. pandas重置索引的几种方法探究

    pandas重置索引的几种方法探究 reset_index() reindex() set_index() 函数名字看起来非常有趣吧! 不仅如此. 需要探究. http://nbviewer.jupy ...

  2. (三)pandas 层次化索引

    pandas层次化索引 1. 创建多层行索引 1) 隐式构造 最常见的方法是给DataFrame构造函数的index参数传递两个或更多的数组 Series也可以创建多层索引 import numpy ...

  3. pandas 数据索引与选取

    我们对 DataFrame 进行选择,大抵从这三个层次考虑:行列.区域.单元格.其对应使用的方法如下:一. 行,列 --> df[]二. 区域   --> df.loc[], df.ilo ...

  4. pandas重新索引

    #重新索引会更改DataFrame的行标签和列标签.重新索引意味着符合数据以匹配特定轴上的一组给定的标签. #可以通过索引来实现多个操作 - #重新排序现有数据以匹配一组新的标签. #在没有标签数据的 ...

  5. pandas DataFrame 索引(iloc 与 loc 的区别)

    Pandas--ix vs loc vs iloc区别 0. DataFrame DataFrame 的构造主要依赖如下三个参数: data:表格数据: index:行索引: columns:列名: ...

  6. Pandas重建索引

    重新索引会更改DataFrame的行标签和列标签.重新索引意味着符合数据以匹配特定轴上的一组给定的标签. 可以通过索引来实现多个操作 - 重新排序现有数据以匹配一组新的标签. 在没有标签数据的标签位置 ...

  7. pandas层级索引1

    层级索引(hierarchical indexing) 下面创建一个Series, 在输入索引Index时,输入了由两个子list组成的list,第一个子list是外层索引,第二个list是内层索引. ...

  8. pandas层级索引

    层级索引(hierarchical indexing) 下面创建一个Series, 在输入索引Index时,输入了由两个子list组成的list,第一个子list是外层索引,第二个list是内层索引. ...

  9. python库学习笔记——Pandas数据索引:ix、loc、iloc区别

    Different Choices for Indexing 1. loc--通过行标签索引行数据 1.1 loc[1]表示索引的是第1行(index 是整数) import pandas as pd ...

随机推荐

  1. VMPlayer Ubuntu 16.04 Copy and Paste with Host 主机与宿机之间的复制粘贴

    使用Ubuntu的虚拟机时如果不能主机之间进行复制粘粘,会非常非常的不方便,所以我们需要安装vmware tools,使用如下的代码(注意第二句一定要有,不然还是不能复制粘贴): sudo apt-g ...

  2. maven deploy 上传jar包到私有仓库

    mvn \ deploy:deploy-file \ -DgroupId=com.weibo.datasys \ -DartifactId=data-flow \ -Dversion=2.0.0 \ ...

  3. RabbitMQ之路由键转发消息

    RabbitMQ学习 参考:https://www.jianshu.com/p/6b62a0ed2491 消息队列:目前流行的有 Kafka.RabbitMQ.ActiveMQ等 功能:为了解决消息的 ...

  4. mysql小细节随笔

    1, MySQL decimal(x,y)  存入根据y的下一位四舍五入,查了半天以为是laravel模型做了预处理,结果发现不是,是mysql decimal类型数据自动处理的,有好,也不好,合并订 ...

  5. arcpy加载mxd文件时,无效的MXD路径,提示assert (os.path.isfile(mxd) or (mxd.lower() == "current")), gp.getIDMessage(89004, "Invalid MXD filename")

    无效的MXD路径,将路径前加‘u’,改为这种: mxdPath = u"C:\\1331\\DB\\Original Files\\dd.mxd" 参考: https://gis. ...

  6. Oracle11g 配置DG broker

    在配置DG broker之前需要确保Dataguard配置正常且主库和备库均使用spfile. 1. 主库配置 配置DG_BROKER_START参数 检查主库dg_broker_start设置 SQ ...

  7. ES6 数组

    数组创建 Array.of() 将参数中所有值作为元素形成数组. console.log(Array.of(1, 2, 3, 4)); // [1, 2, 3, 4] // 参数值可为不同类型 con ...

  8. Spring Boot 2.0 新特性和发展方向

    以Java 8 为基准 Spring Boot 2.0 要求Java 版本必须8以上, Java 6 和 7 不再支持. 内嵌容器包结构调整 为了支持reactive使用场景,内嵌的容器包结构被重构了 ...

  9. npm 镜像的问题

    1> cnpm(不推荐) npm install -g cnpm --registry=https://registry.npm.taobao.org 2> 推荐第二种 npm confi ...

  10. Ethzasl MSF源码阅读(3):MSF_Core和PoseMeasurement

    1.MSF_Core的三个函数:ProcessIMU.ProcessExternallyPropagatedState和AddMeasurement MSF_Core维护了状态队列和观测值队列,这里需 ...