Error while retrying using Pandas series

When I get the first and second elements of this series, it works fine, but from element 3 onwards, throwing an error when I try to make a selection.

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

+6
source share
2 answers

consider the X_test_raw series

 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 does not have index 2 , which you are trying to set with X_test_raw[2] .

Use iloc

 X_test_raw.iloc[2] "PLEASE DON'T FAIL" 

You can iterate through a series using 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 
+6
source

There is no index with a value of 2 .

Example:

 X_test_raw = pd.Series([4,8,9], index=[0,4,5]) print (X_test_raw) 0 4 4 8 5 9 dtype: int64 #print (X_test_raw[2]) #KeyError: 2 

If a third value is required, use iloc :

 print (X_test_raw.iloc[2]) 9 

If you want to repeat only the values:

 for x in X_test_raw: print (x) 4 8 9 

If necessary, indexes and values use Series.iteritems :

 for idx, x in X_test_raw.iteritems(): print (idx, x) 0 4 4 8 5 9 
+5
source

All Articles