重新索引

pandas对象的一个重要方法是 reindex ,其作用是创建一个新对象,它的数据符合新的索引。看下面的例子

  1. In [16]: obj = pd.Series([4.5, 2.2, 4.1, 1.4], index=['d', 'b', 'c', 'a'])
  2. In [17]: obj
  3. Out[17]:
  4. d 4.5
  5. b 2.2
  6. c 4.1
  7. a 1.4
  8. dtype: float64
  9. In [18]: obj2 = obj.reindex(['a', 'b', 'c', 'c'])
  10. In [19]: obj2
  11. Out[19]:
  12. a 1.4
  13. b 2.2
  14. c 4.1
  15. c 4.1
  16. dtype: float64

对于时间序列这样的有序数据,重新索引时可能需要做一些插值处理。 method 选项即可达到此目的。例如,使用 ffukk 可以实现前向值填充

  1. In [20]: obj3 = pd.Series(['blue', 'purple', 'yellow'], index=[0,2,4])
  2. In [21]: obj3
  3. Out[21]:
  4. 0 blue
  5. 2 purple
  6. 4 yellow
  7. dtype: object
  8. In [22]: obj3.reindex(range(6), method='ffill')
  9. Out[22]:
  10. 0 blue
  11. 1 blue
  12. 2 purple
  13. 3 purple
  14. 4 yellow
  15. 5 yellow
  16. dtype: object

借助DataFramereindex 可以修改(行) 索引和列。只传递一个序列时,会重新索引结果的行

  1. In [23]: frame = pd.DataFrame(np.arange(9).reshape((3,3)),
  2. ...: index=['a', 'c', 'd'],
  3. ...: columns=['Ohio', 'Texas', 'California'])
  4. In [24]: frame
  5. Out[24]:
  6. Ohio Texas California
  7. a 0 1 2
  8. c 3 4 5
  9. d 6 7 8
  10. In [25]: frame2 = frame.reindex(['a', 'b', 'c', 'd'])
  11. In [26]: frame2
  12. Out[26]:
  13. Ohio Texas California
  14. a 0.0 1.0 2.0
  15. b NaN NaN NaN
  16. c 3.0 4.0 5.0
  17. d 6.0 7.0 8.0

列可以用 columns 关键字重新索引

  1. In [27]: states = ['Texas', 'Utah', 'California']
  2. In [28]: frame.reindex(columns=states)
  3. Out[28]:
  4. Texas Utah California
  5. a 1 NaN 2
  6. c 4 NaN 5
  7. d 7 NaN 8

reindex 函数的参数
image.png

丢弃指定轴上的项

丢弃某条轴上的一个或多个项很简单,只要有一个索引数组或列表即可。由于需要执行一些数据整理和集合逻辑,所以 drop 方法返回的是一个在指定轴上删除了指定值的新对象

  1. In [3]: obj = pd.Series(np.arange(5.), index=['a', 'b', 'c', 'd', 'e'])
  2. In [4]: obj
  3. Out[4]:
  4. a 0.0
  5. b 1.0
  6. c 2.0
  7. d 3.0
  8. e 4.0
  9. dtype: float64
  10. In [5]: new_obj = obj.drop('c')
  11. In [6]: new_obj
  12. Out[6]:
  13. a 0.0
  14. b 1.0
  15. d 3.0
  16. e 4.0
  17. dtype: float64

对于DataFrame,可以删除任意轴上的索引值。为了演示,先新建一个DataFrame例子

  1. In [7]: data = pd.DataFrame(np.arange(16).reshape((4,4)),
  2. ...: index=['Ohio', 'Colorado', 'Utah', 'New York'],
  3. ...: columns=['one', 'two', 'three', 'four'])
  4. In [8]: data
  5. Out[8]:
  6. one two three four
  7. Ohio 0 1 2 3
  8. Colorado 4 5 6 7
  9. Utah 8 9 10 11
  10. New York 12 13 14 15

用标签序列调用 drop 会从行标签(axis=0)删除值

  1. In [9]: data.drop(['Colorado', 'Ohio'])
  2. Out[9]:
  3. one two three four
  4. Utah 8 9 10 11
  5. New York 12 13 14 15

通过传递axis=1axis=’columns’可以删除列的值

  1. In [10]: data.drop('two', axis=1)
  2. Out[10]:
  3. one three four
  4. Ohio 0 2 3
  5. Colorado 4 6 7
  6. Utah 8 10 11
  7. New York 12 14 15
  8. In [11]: data.drop(['two', 'four'], axis='columns')
  9. Out[11]:
  10. one three
  11. Ohio 0 2
  12. Colorado 4 6
  13. Utah 8 10
  14. New York 12 14

许多函数,如drop ,会修改SeriesDataFrame的大小或形状,可以就地修改对象,不会返回新的对象

  1. In [12]: obj.drop('c', inplace=True)
  2. In [13]: obj
  3. Out[13]:
  4. a 0.0
  5. b 1.0
  6. d 3.0
  7. e 4.0
  8. dtype: float64

小心使用inplace, 它会销毁所有被删除的数据

索引、选取和过滤

Series索引( obj[...] )的工作方式类似于NumPy数组的索引,只不过Series的索引值不只是整数。下面是几个例子

  1. In [14]: obj = pd.Series(np.arange(4.), index=['a', 'b', 'c', 'd'])
  2. In [15]: obj
  3. Out[15]:
  4. a 0.0
  5. b 1.0
  6. c 2.0
  7. d 3.0
  8. dtype: float64
  9. In [16]: obj['b']
  10. Out[16]: 1.0
  11. In [17]: obj[1]
  12. Out[17]: 1.0
  13. In [18]: obj[2:4]
  14. Out[18]:
  15. c 2.0
  16. d 3.0
  17. dtype: float64
  18. In [19]: obj[['b', 'a', 'd']]
  19. Out[19]:
  20. b 1.0
  21. a 0.0
  22. d 3.0
  23. dtype: float64
  24. In [20]: obj[[1,3]]
  25. Out[20]:
  26. b 1.0
  27. d 3.0
  28. dtype: float64
  29. In [21]: obj[obj < 2]
  30. Out[21]:
  31. a 0.0
  32. b 1.0
  33. dtype: float64

利用标签的切片运算与普通的Python切片运算不同,其末端是包含的

  1. In [22]: obj['b':'c']
  2. Out[22]:
  3. b 1.0
  4. c 2.0
  5. dtype: float64

用切片可以对Series的相应部分进行设置

  1. In [23]: obj['b':'c'] = 5
  2. In [24]: obj
  3. Out[24]:
  4. a 0.0
  5. b 5.0
  6. c 5.0
  7. d 3.0
  8. dtype: float64

用一个值或序列对DataFrame进行索引其实就是获取一个或多个列

  1. In [25]: data = pd.DataFrame(np.arange(16).reshape((4,4)),
  2. ...: index=['Ohio', 'Colorado', 'Utah', 'New York'],
  3. ...: columns=['one', 'two', 'three', 'four'])
  4. In [26]: data
  5. Out[26]:
  6. one two three four
  7. Ohio 0 1 2 3
  8. Colorado 4 5 6 7
  9. Utah 8 9 10 11
  10. New York 12 13 14 15
  11. In [27]: data['two']
  12. Out[27]:
  13. Ohio 1
  14. Colorado 5
  15. Utah 9
  16. New York 13
  17. Name: two, dtype: int32
  18. In [28]: data[['three', 'one']]
  19. Out[28]:
  20. three one
  21. Ohio 2 0
  22. Colorado 6 4
  23. Utah 10 8
  24. New York 14 12

这种索引方式有几个特殊的情况。首先通过切片或布尔型数组选取数据

  1. In [29]: data[:2]
  2. Out[29]:
  3. one two three four
  4. Ohio 0 1 2 3
  5. Colorado 4 5 6 7
  6. In [30]: data[data['three'] > 5]
  7. Out[30]:
  8. one two three four
  9. Colorado 4 5 6 7
  10. Utah 8 9 10 11
  11. New York 12 13 14 15

选取行的语法 data[:2] 十分方便。向 [] 传递单一的元素或列表,就可选择列
另一种用法是通过布尔型DataFrame(比如下面这个由标量比较运算得出的)进行索引

  1. In [32]: data < 5
  2. Out[32]:
  3. one two three four
  4. Ohio True True True True
  5. Colorado True False False False
  6. Utah False False False False
  7. New York False False False False
  8. In [33]: data[data < 5] = 0
  9. In [34]: data
  10. Out[34]:
  11. one two three four
  12. Ohio 0 0 0 0
  13. Colorado 0 5 6 7
  14. Utah 8 9 10 11
  15. New York 12 13 14 15

这使得DataFrame的语法与NumPy二维数组的语法很像

用loc和iloc进行选取

对于DataFrame的行的标签索引, 我引入了特殊的标签运算符 lociloc 。它们可以让你用类似NumPy的标记,使用轴标签( loc )或整数索引( iloc ),从DataFrame选择行和列的子集
作为一个初步示例, 让我们通过标签选择一行和多列

  1. In [36]: data.loc['Colorado', ['two', 'three']]
  2. Out[36]:
  3. two 5
  4. three 6
  5. Name: Colorado, dtype: int32

然后用 iloc 和整数进行选取

  1. In [4]: data.iloc[2, [3, 0, 1]]
  2. Out[4]:
  3. four 11
  4. one 8
  5. two 9
  6. Name: Utah, dtype: int32
  7. In [5]: data.iloc[2]
  8. Out[5]:
  9. one 8
  10. two 9
  11. three 10
  12. four 11
  13. Name: Utah, dtype: int32
  14. In [6]: data.iloc[[1,2], [3,0,1]]
  15. Out[6]:
  16. four one two
  17. Colorado 7 4 5
  18. Utah 11 8 9

这两个索引函数也适用于一个标签或多个标签的切片

  • 这有点类似SQLwhere ```python In [7]: data.loc[‘Utah’, ‘two’] Out[7]: 9

In [8]: data.iloc[:, :3][data.three > 5] Out[8]: one two three Colorado 4 5 6 Utah 8 9 10 New York 12 13 14

  1. 下表展示了对**DataFrame**进行选取和重新组合的多个方法<br />![image.png](https://cdn.nlark.com/yuque/0/2020/png/805730/1590826395826-6e460aa7-e4ed-408e-a91f-0e84cde2901a.png#align=left&display=inline&height=410&margin=%5Bobject%20Object%5D&name=image.png&originHeight=547&originWidth=905&size=405861&status=done&style=none&width=679)
  2. <a name="XBuun"></a>
  3. # 整数索引
  4. **pandas**可以勉强进行整数索引,但是会导致小bug。我们有包含0,1,2的索引,但是引入用户想要的东西(基于标签或位置的索引)很难。下面的代码会出错。因为玩意-1也是索引值呢?
  5. ```python
  6. ser = pd.Series(np.arange(3.))
  7. ser
  8. ser[-1]

另外,对于非整数索引,不会产生歧义

  1. In [11]: ser2 = pd.Series(np.arange(3.), index=['a', 'b', 'c'])
  2. In [12]: ser2[-1]
  3. Out[12]: 2.0

为了进行统一,如果轴索引含有整数,数据选取总会使用标签。为了更准确,请使用 **loc** (标签)或 iloc (整数)

算术运算和数据对齐

pandas最重要的一个功能是,它可以对不同索引的对象进行算术运算。在将对象相加时,如果存在不同的索引对,则结果的索引就是该索引对的并集。对于有数据库经验的用户,这就像在索引标签上进行自动外连接。 看一个简单的例子

  1. In [13]: s1 = pd.Series([7.3, -2.5, 3.4, 2.1], index=['a', 'c', 'd', 'e'])
  2. In [14]: s2 = pd.Series([-2.1, 2.2, 1.3, 4.5, 5.3], index=['a', 'c', 'e', 'f', 'g'])
  3. In [15]: s1
  4. Out[15]:
  5. a 7.3
  6. c -2.5
  7. d 3.4
  8. e 2.1
  9. dtype: float64
  10. In [16]: s2
  11. Out[16]:
  12. a -2.1
  13. c 2.2
  14. e 1.3
  15. f 4.5
  16. g 5.3
  17. dtype: float64

现在让它们做加法

  1. In [17]: s1 + s2
  2. Out[17]:
  3. a 5.2
  4. c -0.3
  5. d NaN
  6. e 3.4
  7. f NaN
  8. g NaN
  9. dtype: float64

自动的数据对齐操作在不重叠的索引处引入了NA值。缺失值会在算术运算过程中传播
对于DataFrame,对齐操作会同时发生在行和列上

  1. In [18]: df1 = pd.DataFrame(np.arange(9.).reshape((3,3)), columns=list('bcd'),
  2. ...: index=['Ohio', 'Texas', 'Colorado'])
  3. In [19]: df2 = pd.DataFrame(np.arange(12.).reshape((4,3)), columns=list('bde'),
  4. ...: index=['Utah', 'Ohio', 'Texas', 'Oregon'])
  5. In [20]: df1
  6. Out[20]:
  7. b c d
  8. Ohio 0.0 1.0 2.0
  9. Texas 3.0 4.0 5.0
  10. Colorado 6.0 7.0 8.0
  11. In [21]: df2
  12. Out[21]:
  13. b d e
  14. Utah 0.0 1.0 2.0
  15. Ohio 3.0 4.0 5.0
  16. Texas 6.0 7.0 8.0
  17. Oregon 9.0 10.0 11.0

把它们相加后将会返回一个新的DataFrame,其索引和列为原来那两个DataFrame的并集

  1. In [22]: df1 + df2
  2. Out[22]:
  3. b c d e
  4. Colorado NaN NaN NaN NaN
  5. Ohio 3.0 NaN 6.0 NaN
  6. Oregon NaN NaN NaN NaN
  7. Texas 9.0 NaN 12.0 NaN
  8. Utah NaN NaN NaN NaN

因为’c‘和’e‘列均不在两个DataFrame对象中,在结果中以缺省值呈现。 行也是同样
如果DataFrame对象相加, 没有共用的列或行标签, 结果都会是空

  1. In [24]: df1 = pd.DataFrame({'A':[1,2]})
  2. In [25]: df2 = pd.DataFrame({'B': [3,4]})
  3. In [26]: df1
  4. Out[26]:
  5. A
  6. 0 1
  7. 1 2
  8. In [27]: df2
  9. Out[27]:
  10. B
  11. 0 3
  12. 1 4
  13. In [28]: df1 - df2
  14. Out[28]:
  15. A B
  16. 0 NaN NaN
  17. 1 NaN NaN

在算数方法中填充值

在对不同索引的对象进行算术运算时,你可能希望当一个对象中某个轴标签在另一个对象中找不到时填充一个特殊值(比如0)

  1. In [29]: df1 = pd.DataFrame(np.arange(12.).reshape((3,4)), columns=list('abcd'))
  2. In [30]: df2 = pd.DataFrame(np.arange(20.).reshape((4,5)), columns=list('abcde'))
  3. In [31]: df2.loc[1, 'b'] = np.nan
  4. In [32]: df1
  5. Out[32]:
  6. a b c d
  7. 0 0.0 1.0 2.0 3.0
  8. 1 4.0 5.0 6.0 7.0
  9. 2 8.0 9.0 10.0 11.0
  10. In [33]: df2
  11. Out[33]:
  12. a b c d e
  13. 0 0.0 1.0 2.0 3.0 4.0
  14. 1 5.0 NaN 7.0 8.0 9.0
  15. 2 10.0 11.0 12.0 13.0 14.0
  16. 3 15.0 16.0 17.0 18.0 19.0

将它们相加时,没有重叠的位置就会产生NA

  1. In [34]: df1 + df2
  2. Out[34]:
  3. a b c d e
  4. 0 0.0 2.0 4.0 6.0 NaN
  5. 1 9.0 NaN 13.0 15.0 NaN
  6. 2 18.0 20.0 22.0 24.0 NaN
  7. 3 NaN NaN NaN NaN NaN

使用 df1add 方法,传入 df2 以及一个fill_value 参数

  • 注意这个方法的结果和上例中直接使用加法运算符的差别
    1. In [35]: df1.add(df2, fill_value=0)
    2. Out[35]:
    3. a b c d e
    4. 0 0.0 2.0 4.0 6.0 4.0
    5. 1 9.0 5.0 13.0 15.0 9.0
    6. 2 18.0 20.0 22.0 24.0 14.0
    7. 3 15.0 16.0 17.0 18.0 19.0
    ```python In [36]: 1 / df1 Out[36]:
    1. a b c d
    0 inf 1.000000 0.500000 0.333333 1 0.250 0.200000 0.166667 0.142857 2 0.125 0.111111 0.100000 0.090909

In [37]: df1.rdiv(1) Out[37]: a b c d 0 inf 1.000000 0.500000 0.333333 1 0.250 0.200000 0.166667 0.142857 2 0.125 0.111111 0.100000 0.090909

  1. 下表列出了**Series**和**DataFrame**的算数方法。它们每个都有一个副本,以字母r开头,它会翻转参数。因此上面两个语句是等价的<br />![image.png](https://cdn.nlark.com/yuque/0/2020/png/805730/1590828062056-7ce5fce4-10d0-4cbd-9d64-97496c4b15da.png#align=left&display=inline&height=288&margin=%5Bobject%20Object%5D&name=image.png&originHeight=384&originWidth=592&size=101952&status=done&style=none&width=444)<br />与此类似,在对**Series**或**DataFrame**重新索引时,也可以指定一个填充值
  2. ```python
  3. In [38]: df1.reindex(columns=df2.columns, fill_value=0)
  4. Out[38]:
  5. a b c d e
  6. 0 0.0 1.0 2.0 3.0 0
  7. 1 4.0 5.0 6.0 7.0 0
  8. 2 8.0 9.0 10.0 11.0 0

DataFrame与Series之间的运算

跟不同维度的NumPy数组一样,DataFrameSeries之间算术运算也是有明确规定的。先看一个启发性的例子

  1. In [44]: arr = np.arange(12.).reshape((3,4))
  2. In [45]: arr[0]
  3. Out[45]: array([0., 1., 2., 3.])
  4. In [46]: arr - arr[0]
  5. Out[46]:
  6. array([[0., 0., 0., 0.],
  7. [4., 4., 4., 4.],
  8. [8., 8., 8., 8.]])

当我们从 arr 减去 arr[0] ,每一行都会执行这个操作。这就叫做广播(broadcasting)DataFrame和Series之间的运算也差不多

  1. In [49]: frame = pd.DataFrame(np.arange(12.).reshape((4,-1)),
  2. ...: columns=list('bde'),
  3. ...: index=['Utah', 'Ohio', 'Texas', 'Oregon'])
  4. In [50]: series = frame.iloc[0]
  5. In [51]: frame
  6. Out[51]:
  7. b d e
  8. Utah 0.0 1.0 2.0
  9. Ohio 3.0 4.0 5.0
  10. Texas 6.0 7.0 8.0
  11. Oregon 9.0 10.0 11.0
  12. In [52]: series
  13. Out[52]:
  14. b 0.0
  15. d 1.0
  16. e 2.0
  17. Name: Utah, dtype: float64

默认情况下,DataFrameSeries之间的算术运算会将Series的索引匹配到DataFrame的列,然后沿着行一直向下广播

  1. In [53]: frame - series
  2. Out[53]:
  3. b d e
  4. Utah 0.0 0.0 0.0
  5. Ohio 3.0 3.0 3.0
  6. Texas 6.0 6.0 6.0
  7. Oregon 9.0 9.0 9.0

如果某个索引值在DataFrame的列或Series的索引中找不到,则参与运算的两个对象就会被重新索引以形成并集

  • 从上例中,SeriesDataFrame中的一行,所以Series中的 indexDataFrame中的 column
  • 下例中,只有’b‘和’e‘匹配到了索引,而这两列对应的分别是0和1,所以 frame 中的列’b’和’e’分别都通过广播,加上了0和1 ```python In [54]: series2 = pd.Series(range(3), index=[‘b’, ‘e’, ‘f’])

In [55]: frame + series2 Out[55]: b d e f Utah 0.0 NaN 3.0 NaN Ohio 3.0 NaN 6.0 NaN Texas 6.0 NaN 9.0 NaN Oregon 9.0 NaN 12.0 NaN

  1. 如果你希望匹配行且在列上广播, 则必须使用算术运算方法
  2. ```python
  3. In [56]: series3 = frame['d']
  4. In [57]: frame
  5. Out[57]:
  6. b d e
  7. Utah 0.0 1.0 2.0
  8. Ohio 3.0 4.0 5.0
  9. Texas 6.0 7.0 8.0
  10. Oregon 9.0 10.0 11.0
  11. In [58]: series3
  12. Out[58]:
  13. Utah 1.0
  14. Ohio 4.0
  15. Texas 7.0
  16. Oregon 10.0
  17. Name: d, dtype: float64
  18. In [59]: frame.sub(series3, axis='index')
  19. Out[59]:
  20. b d e
  21. Utah -1.0 0.0 1.0
  22. Ohio -1.0 0.0 1.0
  23. Texas -1.0 0.0 1.0
  24. Oregon -1.0 0.0 1.0

传入的轴号就是希望匹配的轴。在本例中,我们的目的是匹配DataFrame的行索引( axis='index' oraxis=0 )并进行广播

函数的应用和映射

NumPyufuncs(元素级数组方法) 也可用于操作pandas对象

  1. In [4]: frame = pd.DataFrame(np.random.randn(4,3), columns=list('bde'),
  2. ...: index=['Utah', 'Ohio', 'Texas', 'Oregon'])
  3. In [5]: frame
  4. Out[5]:
  5. b d e
  6. Utah 0.298742 -0.546586 -0.689643
  7. Ohio -0.592324 1.528673 -0.450995
  8. Texas 1.112818 0.870985 0.422259
  9. Oregon 1.096166 -1.183010 0.905282
  10. In [6]: np.abs(frame)
  11. Out[6]:
  12. b d e
  13. Utah 0.298742 0.546586 0.689643
  14. Ohio 0.592324 1.528673 0.450995
  15. Texas 1.112818 0.870985 0.422259
  16. Oregon 1.096166 1.183010 0.905282

另一个常见的操作是,将函数应用到由各列或行所形成的一维数组上。DataFrameapply 方法即可实现此功能

  1. In [7]: f = lambda x: x.max() - x.min()
  2. In [8]: frame.apply(f)
  3. Out[8]:
  4. b 1.705142
  5. d 2.711683
  6. e 1.594925
  7. dtype: float64

这里的函数 f ,计算了一个Series的最大值和最小值的差,在frame 的每列都执行了一次。结果是一个Series, 使用 frame 的列作为索引

如果传递 axis='columns'apply ,这个函数会在每行执行

  1. In [10]: frame.apply(f, axis='columns')
  2. Out[10]:
  3. Utah 0.988385
  4. Ohio 2.120997
  5. Texas 0.690559
  6. Oregon 2.279176
  7. dtype: float64

许多最为常见的数组统计功能都被实现成DataFrame的方法(如 summean ),因此无需使用 apply 方法
传递到apply 的函数不是必须返回一个标量,还可以返回由多个值组成的Series

  1. In [11]: def f(x):
  2. ...: return pd.Series([x.min(), x.max()], index=['min', 'max'])
  3. ...:
  4. In [12]: frame.apply(f)
  5. Out[12]:
  6. b d e
  7. min -0.592324 -1.183010 -0.689643
  8. max 1.112818 1.528673 0.905282

元素级的Python函数也是可以用的。假如你想得到frame 中各个浮点值的格式化字符串,使用applymap 即可

  1. In [13]: format = lambda x : '%.2f' % x
  2. In [14]: frame.applymap(format)
  3. Out[14]:
  4. b d e
  5. Utah 0.30 -0.55 -0.69
  6. Ohio -0.59 1.53 -0.45
  7. Texas 1.11 0.87 0.42
  8. Oregon 1.10 -1.18 0.91

之所以叫做applymap ,是因为Series有一个用于应用元素级函数的map 方法

  1. In [15]: frame['e'].map(format)
  2. Out[15]:
  3. Utah -0.69
  4. Ohio -0.45
  5. Texas 0.42
  6. Oregon 0.91
  7. Name: e, dtype: object

排序和排名

根据条件对数据集排序(sorting) 也是一种重要的内置运算。 要对行或列索引进行排序(按字典顺序),可使用sort_index 方法,它将返回一个已排序的新对象

  1. In [16]: obj = pd.Series(range(4), index=['d', 'a', 'b', 'c'])
  2. In [17]: obj.sort_index()
  3. Out[17]:
  4. a 1
  5. b 2
  6. c 3
  7. d 0
  8. dtype: int64

对于DataFrame,则可以根据任意一个轴上的索引进行排序

  1. In [18]: frame = pd.DataFrame(np.arange(8.).reshape((2,4)),
  2. ...: index=['three', 'one'],
  3. ...: columns=['d', 'a', 'b', 'c'])
  4. In [19]: frame.sort_index()
  5. Out[19]:
  6. d a b c
  7. one 4.0 5.0 6.0 7.0
  8. three 0.0 1.0 2.0 3.0
  9. In [20]: frame.sort_index(axis=1)
  10. Out[20]:
  11. a b c d
  12. three 1.0 2.0 3.0 0.0
  13. one 5.0 6.0 7.0 4.0

数据默认是按升序排序的,但也可以降序排序

  1. In [21]: frame.sort_index(axis=1, ascending=False)
  2. Out[21]:
  3. d c b a
  4. three 0.0 3.0 2.0 1.0
  5. one 4.0 7.0 6.0 5.0

若要按值对Series进行排序,可使用其sort_values 方法

  1. In [23]: obj.sort_values()
  2. Out[23]:
  3. 2 -3
  4. 3 2
  5. 0 4
  6. 1 7
  7. dtype: int64

在排序时,任何缺失值默认都会被放到Series的末尾

  1. In [25]: obj.sort_values()
  2. Out[25]:
  3. 4 -3.0
  4. 5 2.0
  5. 0 4.0
  6. 2 7.0
  7. 1 NaN
  8. 3 NaN
  9. dtype: float64

当排序一个DataFrame时,你可能希望根据一个或多个列中的值进行排序。将一个或多个列的名字传递给sort_valuesby 选项即可达到该目的

  1. In [29]: frame.sort_values(by='b')
  2. Out[29]:
  3. b a
  4. 2 -3 0
  5. 3 2 1
  6. 0 4 0
  7. 1 7 1

要根据多个列进行排序,传入名称的列表即可

  1. In [30]: frame.sort_values(by=['a', 'b'])
  2. Out[30]:
  3. b a
  4. 2 -3 0
  5. 0 4 0
  6. 3 2 1
  7. 1 7 1

排名会从1开始一直到数组中有效数据的数量。接下来介绍SeriesDataFramerank 方法。默认情况下, rank 是通过“为各组分配一个平均排名”的方式破坏平级关系的

  1. In [32]: obj = pd.Series([7, -5, 7, 4 ,2, 0, 4])
  2. In [33]: obj.rank()
  3. Out[33]:
  4. 0 6.5
  5. 1 1.0
  6. 2 6.5
  7. 3 4.5
  8. 4 3.0
  9. 5 2.0
  10. 6 4.5
  11. dtype: float64

也可以根据值在原数据中出现的顺序给出排名

  1. In [34]: obj.rank(method='first')
  2. Out[34]:
  3. 0 6.0
  4. 1 1.0
  5. 2 7.0
  6. 3 4.0
  7. 4 3.0
  8. 5 2.0
  9. 6 5.0
  10. dtype: float64

这里,条目0和2没有使用平均排名6.5,它们被设成了6和7, 因为数据中标签0位于标签2的前面。
你也可以按降序进行排名

  1. In [35]: obj.rank(ascending=False, method='max')
  2. Out[35]:
  3. 0 2.0
  4. 1 7.0
  5. 2 2.0
  6. 3 4.0
  7. 4 5.0
  8. 5 6.0
  9. 6 4.0
  10. dtype: float64

下表列出了所有用于破坏平级关系的method 选项。DataFrame可以在行或列上计算排名
image.png

  1. In [36]: frame = pd.DataFrame({'b': [4.3, 7, -3 ,2], 'a': [0, 1, 0, 1],
  2. ...: 'c': [-2, 5, 8, -2.5]})
  3. In [37]: frame
  4. Out[37]:
  5. b a c
  6. 0 4.3 0 -2.0
  7. 1 7.0 1 5.0
  8. 2 -3.0 0 8.0
  9. 3 2.0 1 -2.5
  10. In [38]: frame.rank(axis='columns')
  11. Out[38]:
  12. b a c
  13. 0 3.0 2.0 1.0
  14. 1 3.0 1.0 2.0
  15. 2 1.0 2.0 3.0
  16. 3 3.0 2.0 1.0

带有重复标签的轴索引

虽然许多pandas函数(如reindex )都要求标签唯一,但这并不是强制性的。我们来看看下面这个简单的带有重复索引值的Series

  1. In [39]: obj = pd.Series(range(5), index=['a', 'a', 'b', 'b', 'c'])
  2. In [40]: obj
  3. Out[40]:
  4. a 0
  5. a 1
  6. b 2
  7. b 3
  8. c 4
  9. dtype: int64

索引的in_unique 属性可以告诉你它的值是否是唯一的

  1. In [42]: obj.index.is_unique
  2. Out[42]: False

对于带有重复值的索引,数据选取的行为将会有些不同。如果某个索引对应多个值,则返回一个Series;而对应单个值的,则返回一个标量值

  1. In [43]: obj['a']
  2. Out[43]:
  3. a 0
  4. a 1
  5. dtype: int64
  6. In [44]: obj['c']
  7. Out[44]: 4

这样会使代码变复杂,因为索引的输出类型会根据标签是否有重复发生变化
DataFrame的行进行索引时也是如此

  1. In [45]: df = pd.DataFrame(np.random.randn(4, 3), index=['a', 'a', 'b', 'b'])
  2. In [46]: df
  3. Out[46]:
  4. 0 1 2
  5. a 0.598633 0.509012 -0.319608
  6. a 0.545685 -0.724553 -0.731425
  7. b -0.971970 0.674816 0.304169
  8. b -0.190280 -2.692565 1.386602
  9. In [47]: df.loc['b']
  10. Out[47]:
  11. 0 1 2
  12. b -0.97197 0.674816 0.304169
  13. b -0.19028 -2.692565 1.386602