python - 遍历 Pandas 系列时出错

标签 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 there got amore wat...'

X_test_raw[1]
Out[46]: 'Ok lar... Joking wif u oni...'

X_test_raw[2]

KeyError: 2

最佳答案

考虑系列 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

改为使用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

关于python - 遍历 Pandas 系列时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39463692/

相关文章:

python - 提高挂载目录的 IO 性能?

python - sklearn-线性回归 : could not convert string to float: '--'

R 使用 if else 语句从列表中删除对象

python - Python中有定时执行器服务吗?

python - wxPython - py2exe - exe 文件旧窗口

python - 将文本文件中的数据转换为数据帧

python - 在 Pandas 中跨组应用平均值

javascript - 关于从输出中隐藏文本字符串的代码的几个问题

C for循环行为异常

python - 在 python 中启动 python 和时区问题