我想在迭代期间删除当前行 - 使用 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/