Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
915 views
in Technique[技术] by (71.8m points)

python - pandas series can't get index

not sure what the problem is here... all i want is the first and only element in this series

>>> a
1    0-5fffd6b57084003b1b582ff1e56855a6!1-AB8769635...
Name: id, dtype: object

>>> len (a)
1

>>> type(a)
<class 'pandas.core.series.Series'>

>>> a[0]

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    a[0]
  File "C:Python27libsite-packagespandascoreseries.py", line 601, in __getitem__
    result = self.index.get_value(self, key)
  File "C:Python27libsite-packagespandascoreindexesase.py", line 2477, in get_value
    tz=getattr(series.dtype, 'tz', None))
  File "pandas\_libsindex.pyx", line 98, in pandas._libs.index.IndexEngine.get_value (pandas\_libsindex.c:4404)
  File "pandas\_libsindex.pyx", line 106, in pandas._libs.index.IndexEngine.get_value (pandas\_libsindex.c:4087)
  File "pandas\_libsindex.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas\_libsindex.c:5126)
  File "pandas\_libshashtable_class_helper.pxi", line 759, in pandas._libs.hashtable.Int64HashTable.get_item (pandas\_libshashtable.c:14031)
  File "pandas\_libshashtable_class_helper.pxi", line 765, in pandas._libs.hashtable.Int64HashTable.get_item (pandas\_libshashtable.c:13975)
KeyError: 0L

why isn't that working? and how do get the first element?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When the index is integer, you cannot use positional indexers because the selection would be ambiguous (should it return based on label or position?). You need to either explicitly use a.iloc[0] or pass the label a[1].

The following works because the index type is object:

a = pd.Series([1, 2, 3], index=['a', 'b', 'c'])

a
Out: 
a    1
b    2
c    3
dtype: int64

a[0]
Out: 1

But for integer index, things are different:

a = pd.Series([1, 2, 3], index=[2, 3, 4])

a[2]  # returns the first entry - label based
Out: 1

a[1]  # raises a KeyError
KeyError: 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...