2017-02-04 56 views
1

我正在學習Python和Scikit學習,我正在做一些簡單的練習。在特定的情況下,我運行下面的代碼:在Python中切片和索引系列

import pandas as pd 
df = pd.read_csv('SMSSpamCollection',delimiter='\t',header=None) # from UCIMachineLearningRepository http://archive.ics.uci.edu/ml/datasets/SMS+Spam+Collection 
import numpy as np 
from sklearn.feature_extraction.text import TfidfVectorizer 
from sklearn.linear_model.logistic import LogisticRegression 
from sklearn.cross_validation import train_test_split, cross_val_score 
X_train_raw, X_test_raw, y_train, y_test = train_test_split(df[1], df[0]) 

我打印:

print(X_test_raw[0:5]) 

輸出:

3035  Get ready for <#> inches of pleasure... 
2577     In sch but neva mind u eat 1st lor.. 
3302    RCT' THNQ Adrian for U text. Rgds Vatian 
90  Yeah do! Don‘t stand to close tho- you‘ll catc... 
2355     R we going with the <#> bus? 
Name: 1, dtype: object 

然後我索引逐個第一系列X_test_raw的元件:

X_test_raw[0] 

'Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...' 

然後

X_test_raw[1] 

'Ok lar... Joking wif u oni...' 

然後

X_test_raw[2] 

KeyError: 2L 

這是怎麼回事?爲什麼我在切片前5個元素序列時以及何時將這個序列的每個元素分別編入索引時會返回不同的值?爲索引系列的三維元素時,爲什麼會出現關鍵錯誤消息?

你的意見可以理解

回答

1

如果使用X_test_raw[2]你試圖讓rowindex=2,但如果缺少GET:

KeyError: 2L

對於選擇的位置需要ilociat

X_test_raw.iloc[2] 

樣品:

s = pd.Series(['a','s','f'], index=[2,3,5]) 
print (s) 
2 a 
3 s 
5 f 
dtype: object 

print (s[2]) 
a 

print (s[1:3]) 
3 s 
5 f 
dtype: object 

print (s.loc[2]) 
a 


print (s.iloc[2]) 
f 

您可以檢查: