我有以下代码:
for (i1, row1), (i2, row2) in pairwise(df.iterrows()):
if row1['months_to_maturity'] == row2['months_to_maturity'] and
row1['coupon'] == row2['coupon']:
df = df.drop(df.index[[i1]])
如果满足以下条件,我想做的是删除行
row1['months_to_maturity'] == row2['months_to_maturity'] and
row1['coupon'] == row2['coupon']
pairwise(df.iterrows())
方法给出 dataframe
的当前行和下一行。
不幸的是,当我执行上面的代码时出现此错误
IndexError: index 12 is out of bounds for axis 1 with size 12
我做了print(len(df.index))
在本节开头得到 12
打印出来,所以我有点困惑为什么 IndexError
加薪。
最佳答案
在我看来,您正在迭代行,匹配条件,然后根据满足的条件删除行。我认为这不是完成您想做的事情的最佳方式。
我建议以完全不同的方式做事。尝试这个,给定数据帧 df,
df = pd.DataFrame({'a': [1,2,3,4,4,4,5,5,5]})
df['b'] = df.a
print (df)
a b
0 1 1
1 2 2
2 3 3
3 4 4
4 4 4
5 4 4
6 5 5
7 5 5
8 5 5
为了到达下一行,我可以这样做,
df_next = df.shift()
print (df_next)
a b
0 NaN NaN
1 1 1
2 2 2
3 3 3
4 4 4
5 4 4
6 4 4
7 5 5
8 5 5
要找到匹配的行并将其删除,我可以这样做,
df2 = df.drop(df.index[(df.b==df_nxt.b) & (df.a==df_nxt.a)])
a b
0 1 1
1 2 2
2 3 3
3 4 4
6 5 5
实际上,这可以归结为两行代码,
df_next = df.shift()
df2 = df.drop(df.index[(df.b==df_nxt.b) & (df.a==df_nxt.a)])
这就是 Pandas 的魔力
关于python - 在 Dataframe 中删除行时出现 IndexError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31186453/