遍历 Pandas 系列时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39463692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error iterating through a Pandas series
提问by Sarang Manjrekar
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.
当我获得本系列的第一个和第二个元素时,它工作正常,但从元素 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 there got amore wat...'
X_test_raw[1]
Out[46]: 'Ok lar... Joking wif u oni...'
X_test_raw[2]
KeyError: 2
关键错误:2
采纳答案by piRSquared
consider the series X_test_raw
考虑系列 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]
.
X_test_raw
没有2
您尝试使用的索引X_test_raw[2]
。
Instead use iloc
而是使用 iloc
X_test_raw.iloc[2]
"PLEASE DON'T FAIL"
You can iterate through the series with iteritems
您可以通过系列迭代 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
回答by jezrael
There is no index with value 2
.
没有带有 value 的索引2
。
Sample:
样本:
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 need third value use iloc
:
如果需要第三个值使用iloc
:
print (X_test_raw.iloc[2])
9
If need iterating only values:
如果只需要迭代值:
for x in X_test_raw:
print (x)
4
8
9
If need indexes
and values
use Series.iteritems
:
如果需要indexes
和values
使用Series.iteritems
:
for idx, x in X_test_raw.iteritems():
print (idx, x)
0 4
4 8
5 9