Python 迭代系列时出错
当我得到这个系列的第一个和第二个元素时,它工作正常,但是从元素3开始,当我尝试获取时会出现一个错误Python 迭代系列时出错,python,pandas,for-loop,indexing,keyerror,Python,Pandas,For Loop,Indexing,Keyerror,当我得到这个系列的第一个和第二个元素时,它工作正常,但是从元素3开始,当我尝试获取时会出现一个错误 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 the
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]
关键错误:2
没有值为
2
的索引
样本:
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
如果需要第三个值,请使用:
如果需要仅迭代值:
for x in X_test_raw:
print (x)
4
8
9
如果需要索引
和值
使用:
考虑系列
X\u测试\u原始
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\u test\u raw
没有索引2
,您正试图使用X\u test\u raw[2]
引用该索引
改用iloc
X_test_raw.iloc[2]
"PLEASE DON'T FAIL"
您可以使用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
有什么方法可以让我按顺序遍历这个系列吗?是的,我添加了解决方案。
X_test_raw.iloc[2]
"PLEASE DON'T FAIL"
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