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. 创建多进程Process

    注册一个进程: from multiprocessing import Process import os def func(args): # 在子进程里面.args接收一个参数,如果要接受多个参数使 ...

  2. dedecms (织梦)漏洞&exp整理

    [通杀]dedecms plussearch.php 注入漏洞利用方式看结果如果提示Safe Alert: Request Error step 2 !那么直接用下面的exp查看源代码打印帮助1 /p ...

  3. Spring AOP 随记

    本周经历各种面试失败后,最后一站张建飞老大的阿里,感觉有着这般年纪不该有的垃圾履历而忧伤中,不过还是要继续加油的,毕竟他说的好,都是经历,无愧初心. 所以为了更加深入理解Spring AOP我又翻起了 ...

  4. Palindromic Matrix

    Palindromic Matrix time limit per test 2 seconds memory limit per test 256 megabytes input standard ...

  5. java 中重写toString()方法

    toString()方法 一般出现在System.out.println(类名.toString()); toString()是一种自我描述方法 本身返回的是 getClass().getName() ...

  6. POJ 2248 - Addition Chains - [迭代加深DFS]

    题目链接:http://bailian.openjudge.cn/practice/2248 题解: 迭代加深DFS. DFS思路:从目前 $x[1 \sim p]$ 中选取两个,作为一个新的值尝试放 ...

  7. linux命令:压缩解压打包工具大集合

    目录 (1)zip 压缩.解压缩及归档工具有很多,今天小编就整理几个大家较为常用的. compress gzip  bzip2 xz zip tar cpio 一.压缩.解压工具 用法 压缩 工具 压 ...

  8. word简单优化--提高效率

    1.文件 ---选项---校对(去掉下面这些项) 2.点击自动更正,去掉如下 3.文件--选项--保存

  9. [py]GTM和UTC及python的时间戳

    时间戳是一串字符串 time.time() 时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总毫秒数.通俗的讲, 时间戳是一 ...

  10. (转)Docker容器的重启策略及docker run的--restart选项详解

    1. Docker容器的重启策略 Docker容器的重启策略是面向生产环境的一个启动策略,在开发过程中可以忽略该策略. Docker容器的重启都是由Docker守护进程完成的,因此与守护进程息息相关. ...