- 5.2 基本功能
- 重新索引
- 丢弃指定轴上的项
- 索引、选取和过滤
- 用loc和iloc进行选取
- 整数索引
- 算术运算和数据对齐
- 在算术方法中填充值
- DataFrame和Series之间的运算
- 函数应用和映射
- 排序和排名
- 带有重复标签的轴索引
5.2 基本功能
本节中,我将介绍操作Series和DataFrame中的数据的基本手段。后续章节将更加深入地挖掘pandas在数据分析和处理方面的功能。本书不是pandas库的详尽文档,主要关注的是最重要的功能,那些不大常用的内容(也就是那些更深奥的内容)就交给你自己去摸索吧。
重新索引
pandas对象的一个重要方法是reindex,其作用是创建一个新对象,它的数据符合新的索引。看下面的例子:
In [91]: obj = pd.Series([4.5, 7.2, -5.3, 3.6], index=['d', 'b', 'a', 'c'])In [92]: objOut[92]:d 4.5b 7.2a -5.3c 3.6dtype: float64
用该Series的reindex将会根据新索引进行重排。如果某个索引值当前不存在,就引入缺失值:
In [93]: obj2 = obj.reindex(['a', 'b', 'c', 'd', 'e'])In [94]: obj2Out[94]:a -5.3b 7.2c 3.6d 4.5e NaNdtype: float64
对于时间序列这样的有序数据,重新索引时可能需要做一些插值处理。method选项即可达到此目的,例如,使用ffill可以实现前向值填充:
In [95]: obj3 = pd.Series(['blue', 'purple', 'yellow'], index=[0, 2, 4])In [96]: obj3Out[96]:0 blue2 purple4 yellowdtype: objectIn [97]: obj3.reindex(range(6), method='ffill')Out[97]:0 blue1 blue2 purple3 purple4 yellow5 yellowdtype: object
借助DataFrame,reindex可以修改(行)索引和列。只传递一个序列时,会重新索引结果的行:
In [98]: frame = pd.DataFrame(np.arange(9).reshape((3, 3)),....: index=['a', 'c', 'd'],....: columns=['Ohio', 'Texas', 'California'])In [99]: frameOut[99]:Ohio Texas Californiaa 0 1 2c 3 4 5d 6 7 8In [100]: frame2 = frame.reindex(['a', 'b', 'c', 'd'])In [101]: frame2Out[101]:Ohio Texas Californiaa 0.0 1.0 2.0b NaN NaN NaNc 3.0 4.0 5.0d 6.0 7.0 8.0
列可以用columns关键字重新索引:
In [102]: states = ['Texas', 'Utah', 'California']In [103]: frame.reindex(columns=states)Out[103]:Texas Utah Californiaa 1 NaN 2c 4 NaN 5d 7 NaN 8
表5-3列出了reindex函数的各参数及说明。

丢弃指定轴上的项
丢弃某条轴上的一个或多个项很简单,只要有一个索引数组或列表即可。由于需要执行一些数据整理和集合逻辑,所以drop方法返回的是一个在指定轴上删除了指定值的新对象:
In [105]: obj = pd.Series(np.arange(5.), index=['a', 'b', 'c', 'd', 'e'])In [106]: objOut[106]:a 0.0b 1.0c 2.0d 3.0e 4.0dtype: float64In [107]: new_obj = obj.drop('c')In [108]: new_objOut[108]:a 0.0b 1.0d 3.0e 4.0dtype: float64In [109]: obj.drop(['d', 'c'])Out[109]:a 0.0b 1.0e 4.0dtype: float64
对于DataFrame,可以删除任意轴上的索引值。为了演示,先新建一个DataFrame例子:
In [110]: data = pd.DataFrame(np.arange(16).reshape((4, 4)),.....: index=['Ohio', 'Colorado', 'Utah', 'New York'],.....: columns=['one', 'two', 'three', 'four'])In [111]: dataOut[111]:one two three fourOhio 0 1 2 3Colorado 4 5 6 7Utah 8 9 10 11New York 12 13 14 15
用标签序列调用drop会从行标签(axis 0)删除值:
In [112]: data.drop(['Colorado', 'Ohio'])Out[112]:one two three fourUtah 8 9 10 11New York 12 13 14 15
通过传递axis=1或axis=’columns’可以删除列的值:
In [113]: data.drop('two', axis=1)Out[113]:one three fourOhio 0 2 3Colorado 4 6 7Utah 8 10 11New York 12 14 15In [114]: data.drop(['two', 'four'], axis='columns')Out[114]:one threeOhio 0 2Colorado 4 6Utah 8 10New York 12 14
许多函数,如drop,会修改Series或DataFrame的大小或形状,可以就地修改对象,不会返回新的对象:
In [115]: obj.drop('c', inplace=True)In [116]: objOut[116]:a 0.0b 1.0d 3.0e 4.0dtype: float64
小心使用inplace,它会销毁所有被删除的数据。
索引、选取和过滤
Series索引(obj[…])的工作方式类似于NumPy数组的索引,只不过Series的索引值不只是整数。下面是几个例子:
In [117]: obj = pd.Series(np.arange(4.), index=['a', 'b', 'c', 'd'])In [118]: objOut[118]:a 0.0b 1.0c 2.0d 3.0dtype: float64In [119]: obj['b']Out[119]: 1.0In [120]: obj[1]Out[120]: 1.0In [121]: obj[2:4]Out[121]:c 2.0d 3.0dtype: float64In [122]: obj[['b', 'a', 'd']]Out[122]:b 1.0a 0.0d 3.0dtype: float64In [123]: obj[[1, 3]]Out[123]:b 1.0d 3.0dtype: float64In [124]: obj[obj < 2]Out[124]:a 0.0b 1.0dtype: float64
利用标签的切片运算与普通的Python切片运算不同,其末端是包含的:
In [125]: obj['b':'c']Out[125]:b 1.0c 2.0dtype: float64
用切片可以对Series的相应部分进行设置:
In [126]: obj['b':'c'] = 5In [127]: objOut[127]:a 0.0b 5.0c 5.0d 3.0dtype: float64
用一个值或序列对DataFrame进行索引其实就是获取一个或多个列:
In [128]: data = pd.DataFrame(np.arange(16).reshape((4, 4)),.....: index=['Ohio', 'Colorado', 'Utah', 'New York'],.....: columns=['one', 'two', 'three', 'four'])In [129]: dataOut[129]:one two three fourOhio 0 1 2 3Colorado 4 5 6 7Utah 8 9 10 11New York 12 13 14 15In [130]: data['two']Out[130]:Ohio 1Colorado 5Utah 9New York 13Name: two, dtype: int64In [131]: data[['three', 'one']]Out[131]:three oneOhio 2 0Colorado 6 4Utah 10 8New York 14 12
这种索引方式有几个特殊的情况。首先通过切片或布尔型数组选取数据:
In [132]: data[:2]Out[132]:one two three fourOhio 0 1 2 3Colorado 4 5 6 7In [133]: data[data['three'] > 5]Out[133]:one two three fourColorado 4 5 6 7Utah 8 9 10 11New York 12 13 14 15
选取行的语法data[:2]十分方便。向[ ]传递单一的元素或列表,就可选择列。
另一种用法是通过布尔型DataFrame(比如下面这个由标量比较运算得出的)进行索引:
In [134]: data < 5Out[134]:one two three fourOhio True True True TrueColorado True False False FalseUtah False False False FalseNew York False False False FalseIn [135]: data[data < 5] = 0In [136]: dataOut[136]:one two three fourOhio 0 0 0 0Colorado 0 5 6 7Utah 8 9 10 11New York 12 13 14 15
这使得DataFrame的语法与NumPy二维数组的语法很像。
用loc和iloc进行选取
对于DataFrame的行的标签索引,我引入了特殊的标签运算符loc和iloc。它们可以让你用类似NumPy的标记,使用轴标签(loc)或整数索引(iloc),从DataFrame选择行和列的子集。
作为一个初步示例,让我们通过标签选择一行和多列:
In [137]: data.loc['Colorado', ['two', 'three']]Out[137]:two 5three 6Name: Colorado, dtype: int64
然后用iloc和整数进行选取:
In [138]: data.iloc[2, [3, 0, 1]]Out[138]:four 11one 8two 9Name: Utah, dtype: int64In [139]: data.iloc[2]Out[139]:one 8two 9three 10four 11Name: Utah, dtype: int64In [140]: data.iloc[[1, 2], [3, 0, 1]]Out[140]:four one twoColorado 7 0 5Utah 11 8 9
这两个索引函数也适用于一个标签或多个标签的切片:
In [141]: data.loc[:'Utah', 'two']Out[141]:Ohio 0Colorado 5Utah 9Name: two, dtype: int64In [142]: data.iloc[:, :3][data.three > 5]Out[142]:one two threeColorado 0 5 6Utah 8 9 10New York 12 13 14
所以,在pandas中,有多个方法可以选取和重新组合数据。对于DataFrame,表5-4进行了总结。后面会看到,还有更多的方法进行层级化索引。
笔记:在一开始设计pandas时,我觉得用frame[:, col]选取列过于繁琐(也容易出错),因为列的选择是非常常见的操作。我做了些取舍,将花式索引的功能(标签和整数)放到了ix运算符中。在实践中,这会导致许多边缘情况,数据的轴标签是整数,所以pandas团队决定创造loc和iloc运算符分别处理严格基于标签和整数的索引。
ix运算符仍然可用,但并不推荐。

整数索引
处理整数索引的pandas对象常常难住新手,因为它与Python内置的列表和元组的索引语法不同。例如,你可能不认为下面的代码会出错:
ser = pd.Series(np.arange(3.))serser[-1]
这里,pandas可以勉强进行整数索引,但是会导致小bug。我们有包含0,1,2的索引,但是引入用户想要的东西(基于标签或位置的索引)很难:
In [144]: serOut[144]:0 0.01 1.02 2.0dtype: float64
另外,对于非整数索引,不会产生歧义:
In [145]: ser2 = pd.Series(np.arange(3.), index=['a', 'b', 'c'])In [146]: ser2[-1]Out[146]: 2.0
为了进行统一,如果轴索引含有整数,数据选取总会使用标签。为了更准确,请使用loc(标签)或iloc(整数):
In [147]: ser[:1]Out[147]:0 0.0dtype: float64In [148]: ser.loc[:1]Out[148]:0 0.01 1.0dtype: float64In [149]: ser.iloc[:1]Out[149]:0 0.0dtype: float64
算术运算和数据对齐
pandas最重要的一个功能是,它可以对不同索引的对象进行算术运算。在将对象相加时,如果存在不同的索引对,则结果的索引就是该索引对的并集。对于有数据库经验的用户,这就像在索引标签上进行自动外连接。看一个简单的例子:
In [150]: s1 = pd.Series([7.3, -2.5, 3.4, 1.5], index=['a', 'c', 'd', 'e'])In [151]: s2 = pd.Series([-2.1, 3.6, -1.5, 4, 3.1],.....: index=['a', 'c', 'e', 'f', 'g'])In [152]: s1Out[152]:a 7.3c -2.5d 3.4e 1.5dtype: float64In [153]: s2Out[153]:a -2.1c 3.6e -1.5f 4.0g 3.1dtype: float64
将它们相加就会产生:
In [154]: s1 + s2Out[154]:a 5.2c 1.1d NaNe 0.0f NaNg NaNdtype: float64
自动的数据对齐操作在不重叠的索引处引入了NA值。缺失值会在算术运算过程中传播。
对于DataFrame,对齐操作会同时发生在行和列上:
In [155]: df1 = pd.DataFrame(np.arange(9.).reshape((3, 3)), columns=list('bcd'),.....: index=['Ohio', 'Texas', 'Colorado'])In [156]: df2 = pd.DataFrame(np.arange(12.).reshape((4, 3)), columns=list('bde'),.....: index=['Utah', 'Ohio', 'Texas', 'Oregon'])In [157]: df1Out[157]:b c dOhio 0.0 1.0 2.0Texas 3.0 4.0 5.0Colorado 6.0 7.0 8.0In [158]: df2Out[158]:b d eUtah 0.0 1.0 2.0Ohio 3.0 4.0 5.0Texas 6.0 7.0 8.0Oregon 9.0 10.0 11.0
把它们相加后将会返回一个新的DataFrame,其索引和列为原来那两个DataFrame的并集:
In [159]: df1 + df2Out[159]:b c d eColorado NaN NaN NaN NaNOhio 3.0 NaN 6.0 NaNOregon NaN NaN NaN NaNTexas 9.0 NaN 12.0 NaNUtah NaN NaN NaN NaN
因为’c’和’e’列均不在两个DataFrame对象中,在结果中以缺省值呈现。行也是同样。
如果DataFrame对象相加,没有共用的列或行标签,结果都会是空:
In [160]: df1 = pd.DataFrame({'A': [1, 2]})In [161]: df2 = pd.DataFrame({'B': [3, 4]})In [162]: df1Out[162]:A0 11 2In [163]: df2Out[163]:B0 31 4In [164]: df1 - df2Out[164]:A B0 NaN NaN1 NaN NaN
在算术方法中填充值
在对不同索引的对象进行算术运算时,你可能希望当一个对象中某个轴标签在另一个对象中找不到时填充一个特殊值(比如0):
In [165]: df1 = pd.DataFrame(np.arange(12.).reshape((3, 4)),.....: columns=list('abcd'))In [166]: df2 = pd.DataFrame(np.arange(20.).reshape((4, 5)),.....: columns=list('abcde'))In [167]: df2.loc[1, 'b'] = np.nanIn [168]: df1Out[168]:a b c d0 0.0 1.0 2.0 3.01 4.0 5.0 6.0 7.02 8.0 9.0 10.0 11.0In [169]: df2Out[169]:a b c d e0 0.0 1.0 2.0 3.0 4.01 5.0 NaN 7.0 8.0 9.02 10.0 11.0 12.0 13.0 14.03 15.0 16.0 17.0 18.0 19.0
将它们相加时,没有重叠的位置就会产生NA值:
In [170]: df1 + df2Out[170]:a b c d e0 0.0 2.0 4.0 6.0 NaN1 9.0 NaN 13.0 15.0 NaN2 18.0 20.0 22.0 24.0 NaN3 NaN NaN NaN NaN NaN
使用df1的add方法,传入df2以及一个fill_value参数:
In [171]: df1.add(df2, fill_value=0)Out[171]:a b c d e0 0.0 2.0 4.0 6.0 4.01 9.0 5.0 13.0 15.0 9.02 18.0 20.0 22.0 24.0 14.03 15.0 16.0 17.0 18.0 19.0
表5-5列出了Series和DataFrame的算术方法。它们每个都有一个副本,以字母r开头,它会翻转参数。因此这两个语句是等价的:
In [172]: 1 / df1Out[172]:a b c d0 inf 1.000000 0.500000 0.3333331 0.250000 0.200000 0.166667 0.1428572 0.125000 0.111111 0.100000 0.090909In [173]: df1.rdiv(1)Out[173]:a b c d0 inf 1.000000 0.500000 0.3333331 0.250000 0.200000 0.166667 0.1428572 0.125000 0.111111 0.100000 0.090909

与此类似,在对Series或DataFrame重新索引时,也可以指定一个填充值:
In [174]: df1.reindex(columns=df2.columns, fill_value=0)Out[174]:a b c d e0 0.0 1.0 2.0 3.0 01 4.0 5.0 6.0 7.0 02 8.0 9.0 10.0 11.0 0
DataFrame和Series之间的运算
跟不同维度的NumPy数组一样,DataFrame和Series之间算术运算也是有明确规定的。先来看一个具有启发性的例子,计算一个二维数组与其某行之间的差:
In [175]: arr = np.arange(12.).reshape((3, 4))In [176]: arrOut[176]:array([[ 0., 1., 2., 3.],[ 4., 5., 6., 7.],[ 8., 9., 10., 11.]])In [177]: arr[0]Out[177]: array([ 0., 1., 2., 3.])In [178]: arr - arr[0]Out[178]:array([[ 0., 0., 0., 0.],[ 4., 4., 4., 4.],[ 8., 8., 8., 8.]])
当我们从arr减去arr[0],每一行都会执行这个操作。这就叫做广播(broadcasting),附录A将对此进行详细讲解。DataFrame和Series之间的运算差不多也是如此:
In [179]: frame = pd.DataFrame(np.arange(12.).reshape((4, 3)),.....: columns=list('bde'),.....: index=['Utah', 'Ohio', 'Texas', 'Oregon'])In [180]: series = frame.iloc[0]In [181]: frameOut[181]:b d eUtah 0.0 1.0 2.0Ohio 3.0 4.0 5.0Texas 6.0 7.0 8.0Oregon 9.0 10.0 11.0In [182]: seriesOut[182]:b 0.0d 1.0e 2.0Name: Utah, dtype: float64
默认情况下,DataFrame和Series之间的算术运算会将Series的索引匹配到DataFrame的列,然后沿着行一直向下广播:
In [183]: frame - seriesOut[183]:b d eUtah 0.0 0.0 0.0Ohio 3.0 3.0 3.0Texas 6.0 6.0 6.0Oregon 9.0 9.0 9.0
如果某个索引值在DataFrame的列或Series的索引中找不到,则参与运算的两个对象就会被重新索引以形成并集:
In [184]: series2 = pd.Series(range(3), index=['b', 'e', 'f'])In [185]: frame + series2Out[185]:b d e fUtah 0.0 NaN 3.0 NaNOhio 3.0 NaN 6.0 NaNTexas 6.0 NaN 9.0 NaNOregon 9.0 NaN 12.0 NaN
如果你希望匹配行且在列上广播,则必须使用算术运算方法。例如:
In [186]: series3 = frame['d']In [187]: frameOut[187]:b d eUtah 0.0 1.0 2.0Ohio 3.0 4.0 5.0Texas 6.0 7.0 8.0Oregon 9.0 10.0 11.0In [188]: series3Out[188]:Utah 1.0Ohio 4.0Texas 7.0Oregon 10.0Name: d, dtype: float64In [189]: frame.sub(series3, axis='index')Out[189]:b d eUtah -1.0 0.0 1.0Ohio -1.0 0.0 1.0Texas -1.0 0.0 1.0Oregon -1.0 0.0 1.0
传入的轴号就是希望匹配的轴。在本例中,我们的目的是匹配DataFrame的行索引(axis=’index’ or axis=0)并进行广播。
函数应用和映射
NumPy的ufuncs(元素级数组方法)也可用于操作pandas对象:
In [190]: frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'),.....: index=['Utah', 'Ohio', 'Texas', 'Oregon'])In [191]: frameOut[191]:b d eUtah -0.204708 0.478943 -0.519439Ohio -0.555730 1.965781 1.393406Texas 0.092908 0.281746 0.769023Oregon 1.246435 1.007189 -1.296221In [192]: np.abs(frame)Out[192]:b d eUtah 0.204708 0.478943 0.519439Ohio 0.555730 1.965781 1.393406Texas 0.092908 0.281746 0.769023Oregon 1.246435 1.007189 1.296221
另一个常见的操作是,将函数应用到由各列或行所形成的一维数组上。DataFrame的apply方法即可实现此功能:
In [193]: f = lambda x: x.max() - x.min()In [194]: frame.apply(f)Out[194]:b 1.802165d 1.684034e 2.689627dtype: float64
这里的函数f,计算了一个Series的最大值和最小值的差,在frame的每列都执行了一次。结果是一个Series,使用frame的列作为索引。
如果传递axis=’columns’到apply,这个函数会在每行执行:
In [195]: frame.apply(f, axis='columns')Out[195]:Utah 0.998382Ohio 2.521511Texas 0.676115Oregon 2.542656dtype: float64
许多最为常见的数组统计功能都被实现成DataFrame的方法(如sum和mean),因此无需使用apply方法。
传递到apply的函数不是必须返回一个标量,还可以返回由多个值组成的Series:
In [196]: def f(x):.....: return pd.Series([x.min(), x.max()], index=['min', 'max'])In [197]: frame.apply(f)Out[197]:b d emin -0.555730 0.281746 -1.296221max 1.246435 1.965781 1.393406
元素级的Python函数也是可以用的。假如你想得到frame中各个浮点值的格式化字符串,使用applymap即可:
In [198]: format = lambda x: '%.2f' % xIn [199]: frame.applymap(format)Out[199]:b d eUtah -0.20 0.48 -0.52Ohio -0.56 1.97 1.39Texas 0.09 0.28 0.77Oregon 1.25 1.01 -1.30
之所以叫做applymap,是因为Series有一个用于应用元素级函数的map方法:
In [200]: frame['e'].map(format)Out[200]:Utah -0.52Ohio 1.39Texas 0.77Oregon -1.30Name: e, dtype: object
排序和排名
根据条件对数据集排序(sorting)也是一种重要的内置运算。要对行或列索引进行排序(按字典顺序),可使用sort_index方法,它将返回一个已排序的新对象:
In [201]: obj = pd.Series(range(4), index=['d', 'a', 'b', 'c'])In [202]: obj.sort_index()Out[202]:a 1b 2c 3d 0dtype: int64
对于DataFrame,则可以根据任意一个轴上的索引进行排序:
In [203]: frame = pd.DataFrame(np.arange(8).reshape((2, 4)),.....: index=['three', 'one'],.....: columns=['d', 'a', 'b', 'c'])In [204]: frame.sort_index()Out[204]:d a b cone 4 5 6 7three 0 1 2 3In [205]: frame.sort_index(axis=1)Out[205]:a b c dthree 1 2 3 0one 5 6 7 4
数据默认是按升序排序的,但也可以降序排序:
In [206]: frame.sort_index(axis=1, ascending=False)Out[206]:d c b athree 0 3 2 1one 4 7 6 5
若要按值对Series进行排序,可使用其sort_values方法:
In [207]: obj = pd.Series([4, 7, -3, 2])In [208]: obj.sort_values()Out[208]:2 -33 20 41 7dtype: int64
在排序时,任何缺失值默认都会被放到Series的末尾:
In [209]: obj = pd.Series([4, np.nan, 7, np.nan, -3, 2])In [210]: obj.sort_values()Out[210]:4 -3.05 2.00 4.02 7.01 NaN3 NaNdtype: float64
当排序一个DataFrame时,你可能希望根据一个或多个列中的值进行排序。将一个或多个列的名字传递给sort_values的by选项即可达到该目的:
In [211]: frame = pd.DataFrame({'b': [4, 7, -3, 2], 'a': [0, 1, 0, 1]})In [212]: frameOut[212]:a b0 0 41 1 72 0 -33 1 2In [213]: frame.sort_values(by='b')Out[213]:a b2 0 -33 1 20 0 41 1 7
要根据多个列进行排序,传入名称的列表即可:
In [214]: frame.sort_values(by=['a', 'b'])Out[214]:a b2 0 -30 0 43 1 21 1 7
排名会从1开始一直到数组中有效数据的数量。接下来介绍Series和DataFrame的rank方法。默认情况下,rank是通过“为各组分配一个平均排名”的方式破坏平级关系的:
In [215]: obj = pd.Series([7, -5, 7, 4, 2, 0, 4])In [216]: obj.rank()Out[216]:0 6.51 1.02 6.53 4.54 3.05 2.06 4.5dtype: float64
也可以根据值在原数据中出现的顺序给出排名:
In [217]: obj.rank(method='first')Out[217]:0 6.01 1.02 7.03 4.04 3.05 2.06 5.0dtype: float64
这里,条目0和2没有使用平均排名6.5,它们被设成了6和7,因为数据中标签0位于标签2的前面。
你也可以按降序进行排名:
# Assign tie values the maximum rank in the groupIn [218]: obj.rank(ascending=False, method='max')Out[218]:0 2.01 7.02 2.03 4.04 5.05 6.06 4.0dtype: float64
表5-6列出了所有用于破坏平级关系的method选项。DataFrame可以在行或列上计算排名:
In [219]: frame = pd.DataFrame({'b': [4.3, 7, -3, 2], 'a': [0, 1, 0, 1],.....: 'c': [-2, 5, 8, -2.5]})In [220]: frameOut[220]:a b c0 0 4.3 -2.01 1 7.0 5.02 0 -3.0 8.03 1 2.0 -2.5In [221]: frame.rank(axis='columns')Out[221]:a b c0 2.0 3.0 1.01 1.0 3.0 2.02 2.0 1.0 3.03 2.0 3.0 1.0

带有重复标签的轴索引
直到目前为止,我所介绍的所有范例都有着唯一的轴标签(索引值)。虽然许多pandas函数(如reindex)都要求标签唯一,但这并不是强制性的。我们来看看下面这个简单的带有重复索引值的Series:
In [222]: obj = pd.Series(range(5), index=['a', 'a', 'b', 'b', 'c'])In [223]: objOut[223]:a 0a 1b 2b 3c 4dtype: int64
索引的is_unique属性可以告诉你它的值是否是唯一的:
In [224]: obj.index.is_uniqueOut[224]: False
对于带有重复值的索引,数据选取的行为将会有些不同。如果某个索引对应多个值,则返回一个Series;而对应单个值的,则返回一个标量值:
In [225]: obj['a']Out[225]:a 0a 1dtype: int64In [226]: obj['c']Out[226]: 4
这样会使代码变复杂,因为索引的输出类型会根据标签是否有重复发生变化。
对DataFrame的行进行索引时也是如此:
In [227]: df = pd.DataFrame(np.random.randn(4, 3), index=['a', 'a', 'b', 'b'])In [228]: dfOut[228]:0 1 2a 0.274992 0.228913 1.352917a 0.886429 -2.001637 -0.371843b 1.669025 -0.438570 -0.539741b 0.476985 3.248944 -1.021228In [229]: df.loc['b']Out[229]:0 1 2b 1.669025 -0.438570 -0.539741b 0.476985 3.248944 -1.021228
