python - 在 Dataframe 中删除行时出现 IndexError

标签 python pandas

我有以下代码:

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/

相关文章:

Python 3.5 BytesIO 错误

python - 未知类型名称 'glp_long' (mac osx python, pyglpk)

python GTK : Scrollable Grid with clickable images

python - 基于另一列拆分 pandas DataFrame 列的最短方法

python - glob 多个 CSV 和 np.arange

python - 根据 Pandas Python 中的分组列值执行条件过滤

python - 在 Python 2.x 中如何检查输入是字符串还是整数?

python - 环境激活后gitlab-ci未运行pytest

python - 将 JSON 文件读入 Pandas 进行分析

python-3.x - 带有美元符号的 Pandas 到 MatPlotLib