【问题标题】:Pandas: IndexError: index out of bounds when using iterrows [closed]Pandas:IndexError:使用 iterrows 时索引超出范围 [关闭]
【发布时间】:2019-09-12 20:22:45
【问题描述】:

我遇到了一个奇怪的问题,我不知道究竟是什么原因造成的。我正在尝试使用 iterrows 循环遍历列的子集并根据当前列行中的结果更新新列。它似乎适用于我拥有的一个列表,但不适用于另一个。我已将每个列表中的所有列都转换为字符串,但这似乎并没有解决它。

例子:

list1 = [item for item in list(df) if 'TR_' in item]

list2 = [item for item in list(df) if 'TS_' in item ]



for index, row in df[list1].iterrows():
   print(index, row)
   if pd.isna(row[index]):
      df.loc[index, 'new_col'] = 'good'
   else:
      df.loc[index, 'new_col'] = "bad"


for index, row in df[list2].iterrows():
   print(index, row)
   if pd.isna(row[index]):
      df.loc[index, 'new_col2'] = 'good'
   else:
      df.loc[index, 'new_col2'] = 'bad'

output:

KeyError Traceback(最近调用 最后的) C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py 在 get_value(self, series, key) 3102 返回 self._engine.get_value(s, k, -> 3103 tz=getattr(series.dtype, 'tz', None)) 3104 除了 KeyError 作为e1:

pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas_libs\hashtable_class_helper.pxi 在 pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas_libs\hashtable_class_helper.pxi 在 pandas._libs.hashtable.PyObjectHashTable.get_item()

密钥错误:3

在处理上述异常的过程中,又发生了一个异常:

IndexError Traceback(最近调用 最后)在() 17 用于索引,df[list2].iterrows() 中的行: 18 打印(索引,行) ---> 19 如果 pd.isna(row[index]): 20 df.loc[index, 'new_col2'] = '合规' 其他 21 条:

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py 在 getitem(自我,钥匙) 第764章 765尝试: --> 766 结果 = self.index.get_value(self, key) 767 768如果不是is_scalar(结果):

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py 在 get_value(self, series, key) 3107 3108 中尝试: -> 3109 return libindex.get_value_box(s, key) 3110 除了 IndexError: 3111 raise

pandas_libs\index.pyx in pandas._libs.index.get_value_box()

pandas_libs\index.pyx in pandas._libs.index.get_value_box()

IndexError: 索引超出范围`

【问题讨论】:

  • 仅供参考...您可以使用pd.DataFrame.filter 过滤您的数据框而不是列表理解。 df.filter(like='TR_').columns
  • pd.isna(row[index]) 真的正确吗?你不叫列号索引,在你的行上,索引是行索引吗?
  • @ScottBoston- 谢谢!很高兴知道!
  • @GrzegorzSkibinski 我相信是的。它适用于第一个迭代,给出正确的输出,但不是第二个。

标签: python python-3.x pandas dataframe


【解决方案1】:

我指的是:


>>> df
  cat  col1  col2
0   a     1     2
1   a     3     2
2   b    23     1
3   a     1    23
4   b   121    32
>>> for index, row in df.iterrows():
...    print(row[index])
...
a
3
1
Traceback (most recent call last):
  File "C:\Users\Grzegorz\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\core\indexes\base.py", line 4723, in get_value
    return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
  File "pandas\_libs\index.pyx", line 80, in pandas._libs.index.IndexEngine.get_value
  File "pandas\_libs\index.pyx", line 88, in pandas._libs.index.IndexEngine.get_value
  File "pandas\_libs\index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 1607, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 3

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\Users\Grzegorz\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\core\series.py", line 1064, in __getitem__
    result = self.index.get_value(self, key)
  File "C:\Users\Grzegorz\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\core\indexes\base.py", line 4729, in get_value
    return libindex.get_value_box(s, key)
  File "pandas\_libs\index.pyx", line 51, in pandas._libs.index.get_value_box
  File "pandas\_libs\index.pyx", line 47, in pandas._libs.index.get_value_at
  File "pandas\_libs\util.pxd", line 98, in pandas._libs.util.get_value_at
  File "pandas\_libs\util.pxd", line 89, in pandas._libs.util.validate_indexer
IndexError: index out of bounds

即你用row[index] 错了。您想在那里实现什么目标?

编辑

替换:

pd.isna(row[index])

np.product(pd.isna(row))

这样做 - 你会:

(1) 对于给定的row,每列返回True/False 列表

pd.isna(row)

(2) 计算逻辑乘法(即a1 and a2 and ...)所以True 仅当所有列都是na,否则False

np.product(pd.isna(row))

【讨论】:

  • 啊-我明白了。我正在尝试遍历每列中的所有行,如果它们都是空白的,则创建一个显示“好”的新列,否则创建一个显示“坏”的新列并在一秒钟内捕获所有信息该行的新列
  • 然后尝试做:pd.isna(row) - 如果给定的列是na,您将得到每列带有True/False 的行。问题是 - 你想如何从那里获取它,即一列是 na == bad,还是所有列 na == bad?
  • 啊,成功了!如果所有列都是 na = 好,否则不好 + 将所有评论添加到新单元格
  • 请检查我的编辑 - 这应该可以解决您的问题
【解决方案2】:

尝试在列表之前重置您的索引。

 df=df.reset_index(drop=True) 

【讨论】:

  • 尝试使用 iloc,因为它是基于索引的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-27
  • 2023-03-29
  • 2013-10-19
  • 2021-02-08
相关资源
最近更新 更多