我是 python 新手。这似乎是一个要问的基本问题。但我真的很想了解这里发生了什么
import numpy as np
import pandas as pd
tempdata = np.random.random(5)
myseries_one = pd.Series(tempdata)
myseries_two = pd.Series(data = tempdata, index = ['a','b','c','d','e'])
myseries_three = pd.Series(data = tempdata, index = [10,11,12,13,14])
myseries_one
Out[1]:
0 0.291293
1 0.381014
2 0.923360
3 0.271671
4 0.605989
dtype: float64
myseries_two
Out[2]:
a 0.291293
b 0.381014
c 0.923360
d 0.271671
e 0.605989
dtype: float64
myseries_three
Out[3]:
10 0.291293
11 0.381014
12 0.923360
13 0.271671
14 0.605989
dtype: float64
索引每个数据框中的第一个元素
myseries_one[0] #As expected
Out[74]: 0.29129291112626043
myseries_two[0] #As expected
Out[75]: 0.29129291112626043
myseries_three[0]
KeyError:0
疑问 1:-为什么会发生这种情况?为什么 myseries_three[0] 给我一个 keyError ? 调用 myseries_one[0] 、 myseries_one[0] 或 myseries_three[0] 是什么意思?以这种方式调用是否意味着我们正在通过行名调用?
疑问 2:-Python 中的行名和行号是否与 R 中的行名和行号不同?
myseries_one[0:2]
Out[78]:
0 0.291293
1 0.381014
dtype: float64
myseries_two[0:2]
Out[79]:
a 0.291293
b 0.381014
dtype: float64
myseries_three[0:2]
Out[80]:
10 0.291293
11 0.381014
dtype: float64
疑问 3:- 如果调用 myseries_three[0] 意味着通过行名调用,那么 myseries_three[0:3] 如何产生输出? myseries_three[0:4] 是否意味着我们通过 rownumber 调用?请解释和指导。我正在从 R 迁移到 python。所以我有点困惑。
最佳答案
当您尝试使用 myseries[something]
进行切片时,something
通常是不明确的。您正在强调这种模棱两可的情况。在您的情况下,pandas 正试图通过猜测您的意思来帮助您。
myseries_one[0] #As expected
Out[74]: 0.29129291112626043
myseries_one
有整数标签。有意义的是,当您尝试使用一个整数进行切片时,您打算获得标有该整数的元素。事实证明,您有一个标有 0
的元素,因此它会返回给您。
myseries_two[0] #As expected
Out[75]: 0.29129291112626043
myseries_two
有字符串标签。当标签都是字符串时,您不太可能打算使用 0
标签对这个系列进行切片。因此,pandas 假定您的意思是 0
的位置并返回第一个元素(感谢 pandas,这很有帮助)。
myseries_three[0]
KeyError:0
myseries_three
有整数标签,您正在尝试用整数切片……完美。让我们为您获取该值... KeyError
。糟糕,该索引标签不存在。在这种情况下,对于 pandas 来说,失败比猜测你可能打算按位置切片更安全。该文档甚至建议,如果您想消除歧义,请使用 loc
进行基于标签的切片,使用 iloc
进行基于位置的切片。
让我们试试loc
myseries_one.loc[0]
0.29129291112626043
myseries_two.loc[0]
KeyError:0
myseries_three.loc[0]
KeyError:0
只有 myseries_one
有标签 0
。另外两个返回KeyError
让我们试试 iloc
myseries_one.iloc[0]
0.29129291112626043
myseries_two.iloc[0]
0.29129291112626043
myseries_three.iloc[0]
0.29129291112626043
它们的位置都是0
,并相应地返回第一个元素。
对于范围切片,pandas 决定较少解释并坚持对整数切片 0:2
进行位置切片。记住。做出这些决定的是真实的人(编写 pandas 代码的程序员)。当您尝试做一些模棱两可的事情时,您可能会得到不同的结果。要消除歧义,请使用 loc
和 iloc
。
iloc
myseries_one.iloc[0:2]
0 0.291293
1 0.381014
dtype: float64
myseries_two.iloc[0:2]
a 0.291293
b 0.381014
dtype: float64
myseries_three.iloc[0:2]
10 0.291293
11 0.381014
dtype: float64
loc
myseries_one.loc[0:2]
0 0.291293
1 0.381014
2 0.923360
dtype: float64
myseries_two.loc[0:2]
TypeError: cannot do slice indexing on <class 'pandas.indexes.base.Index'> with these indexers [0] of <type 'int'>
myseries_three.loc[0:2]
Series([], dtype: float64)
关于python - 索引在 Pandas 中是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38917945/