Error iterating through a Pandas series

Sarang Manjrekar picture Sarang Manjrekar · Sep 13, 2016 · Viewed 10.6k times · Source

When I get the first and second elements of this series, it works OK, but from element 3 onwards, giving an error when I try to fetch.

type(X_test_raw)
Out[51]: pandas.core.series.Series

len(X_test_raw)
Out[52]: 1393

X_test_raw[0]
Out[45]: 'Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...'

X_test_raw[1]
Out[46]: 'Ok lar... Joking wif u oni...'

X_test_raw[2]

KeyError: 2

Answer

piRSquared picture piRSquared · Sep 13, 2016

consider the series X_test_raw

X_test_raw = pd.Series(
    ['Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...',
     'Ok lar... Joking wif u oni...',
     'PLEASE DON\'T FAIL'
    ], [0, 1, 3])

X_test_raw doesn't have an index of 2 which you are trying to reference with X_test_raw[2].

Instead use iloc

X_test_raw.iloc[2]

"PLEASE DON'T FAIL"

You can iterate through the series with iteritems

for index_val, series_val in X_test_raw.iteritems():
    print series_val

Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...
Ok lar... Joking wif u oni...
PLEASE DON'T FAIL