【问题标题】:Error iterating through a Pandas series遍历 Pandas 系列时出错
【发布时间】:2016-09-13 06:41:28
【问题描述】:

当我得到这个系列的第一个和第二个元素时,它工作正常,但是从元素 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]

密钥错误:2

【问题讨论】:

    标签: python pandas for-loop indexing keyerror


    【解决方案1】:

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

    【讨论】:

      【解决方案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
      

      如果需要第三个值使用iloc:

      print (X_test_raw.iloc[2])
      9
      

      如果只需要迭代值:

      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
      

      【讨论】:

      • 我有什么办法可以按顺序遍历这个系列吗?
      • 是的,我添加解决方案。
      猜你喜欢
      • 2018-10-20
      • 2018-08-17
      • 2019-03-28
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 2014-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多