Pandas遍历DataFrame按条件在中间插入行的IndexError解决
Pandas按条件插入行触发索引越界问题
我有一个DataFrame,需要基于条件在表格中间位置插入行:当条件满足时,需根据前一行、后一行的字段值生成新行完成插入。最初编写的实现代码如下:
for index, row in df.iterrows(): last_row = df.iloc[index-1] next_row = df.iloc[index+1] new_row = { 'SystemID' : last_row.SystemID, 'StartDateTime' : last_row.EndDateTime, 'EndDateTime' : next_row.StartDateTime, 'Date' : last_row.Date, 'Duration':0, 'EventCodeType':"PL", 'Shift':last_row.Shift, 'ProductCode':last_row.ProductCode, 'Machine&Fault':"Producing" } new_row = {k:v for k,v in new_row.items()} if index == last: break else: if index != 0 : # 判定条件 if (df.iloc[index]['StartDateTime'] != df.iloc[index - 1]['EndDateTime']): df.loc[index+1] = new_row # 该行触发错误 continue
执行插入行操作时抛出错误:运行next_row = df.iloc[index+1]代码时触发IndexError: single positional indexer is out-of-bounds(单位置索引器越界)。
数据集样式如下:
方案调整更新
参考答复思路调整了实现逻辑,代码如下:
for index, row in df.iterrows(): try: if index == df.shape[0]: break else: last_row = df.iloc[index-1] next_row = df.iloc[index] new_row = { 'SystemID' : last_row.SystemID, 'StartDateTime' : last_row.EndDateTime, 'EndDateTime' : next_row.StartDateTime, 'Date' : last_row.Date, 'Duration':0 , 'EventCodeType':"PL", 'Shift':last_row.Shift, 'ProductCode':last_row.ProductCode, 'Machine&Fault':"Producing" } new_row = {k:v for k,v in new_row.items()} if index != 0 and index!=df.shape[0]: if (df.iloc[index]['StartDateTime'] != df.iloc[index - 1]['EndDateTime']): df1 = df1.append(new_row, ignore_index=True) continue except: continue
调整思路为:通过try-catch捕获异常,将符合条件生成的新行追加到新DataFrame中,最后再拼接两个DataFrame。
内容的提问来源于stack exchange,提问作者KGP Vertiv
相关产品推荐
相关产品推荐

