【发布时间】: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