我想在迭代期间删除当前行 - using 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
Run Code Online (Sandbox Code Playgroud)
这可能是一个非常简单的,但我仍然无法弄清楚如何做到这一点.非常感谢您的帮助!
EdC*_*ica 21
我不知道这是否是伪代码,但你不能删除这样的行,你可以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
Run Code Online (Sandbox Code Playgroud)
如果你只想过滤掉那些行,你可以执行布尔索引:
df[df['a'] <=0]
Run Code Online (Sandbox Code Playgroud)
会达到同样的目的
| 归档时间: |
|
| 查看次数: |
21252 次 |
| 最近记录: |