python - 如何在 df.iterrows() 期间删除 Pandas 数据框中的当前行

标签 python pandas

我想在迭代期间删除当前行 - 使用 df.iterrows(),如果它的特定列在我的 if 条件下失败。

例如

for index, row in df:
     if row['A'] == 0:
          #remove/drop this row from the df
          del df[index] #I tried this but it gives me an error

这可能是一件非常简单的事情,但我仍然不知道该怎么做。 非常感谢您的帮助!

最佳答案

我不知道这是不是伪代码但是你不能像这样删除一行,你可以drop它:

In [425]:

df = pd.DataFrame({'a':np.random.randn(5), 'b':np.random.randn(5)})
df
Out[425]:
          a         b
0 -1.348112  0.583603
1  0.174836  1.211774
2 -2.054173  0.148201
3 -0.589193 -0.369813
4 -1.156423 -0.967516
In [426]:

for index, row in df.iterrows():
    if row['a'] > 0:
        df.drop(index, inplace=True)
In [427]:

df
Out[427]:
          a         b
0 -1.348112  0.583603
2 -2.054173  0.148201
3 -0.589193 -0.369813
4 -1.156423 -0.967516

如果您只想过滤掉那些行,您可以执行 bool 索引:

df[df['a'] <=0]

会达到同样的目的

关于python - 如何在 df.iterrows() 期间删除 Pandas 数据框中的当前行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28876243/

相关文章:

python - 在套接字传输中接收额外字节

python - 将年份和日期转换为 Pandas 中的日期时间索引

python - np.array arr.itemsize 与 sys.getsizeof(arr[0])

python - 使用 Python 正则表达式处理 Unicode 字符

python - 在Mac上的pandas中打开csv文件时出现utf-8错误

python - 在数据框单元格中搜索关键字

python-2.7 - Pandas 从 python 中的字符串列中删除数字

python - 从带有子项的字典数组构建嵌套的树状字典

python - 按天汇总 pandas 数据帧时间序列

python - 将元组转换为数据帧