2016-09-13 10 views
6

このシリーズの最初と2番目の要素を取得すると問題なく動作しますが、要素3以降はフェッチしようとするとエラーが発生します。Pandasシリーズを反復するエラー

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

はシリーズ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はあなたがX_test_raw[2]を参照しようとしている2のインデックスを持っていないことを検討してください。

代わりにあなたが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 
+0

ありがとうございました。 – Sarang

5

2とはインデックスがありません。

サンプル:必要は値のみを繰り返す場合

print (X_test_raw.iloc[2]) 
9 

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 

第3の値の使用ilocが必要な場合

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

必要indexesvalues使用Series.iteritems場合:

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

と直列を反復処理することができますiloc

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

を使用して、私はこのシリーズを順番に反復処理するための方法はありますか? – Sarang

+0

はい、私は解決策を追加します。 – jezrael

関連する問題