在遍历 Pandas 数据帧时删除一行 [英] dropping a row while iterating through pandas dataframe
本文介绍了在遍历 Pandas 数据帧时删除一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框 df
名称分布啊啊啊10bbbb 11cccc 41第 77 章
我想删除距离小于 10 的行到下一行.扩展输出为
名称分布啊啊啊10cccc 41第 77 章
为此,我使用了以下代码
<预><代码>>>>对于 idx,df.iterrows() 中的行:...如果 idx但是我遇到了错误.你能帮忙吗?
解决方案
如果您决定要删除哪些行的标准有点棘手,例如与上一行/下一行中的值相关,那么一种简单的方法是简单地建立一个要删除的行的索引列表,然后在最后一次性删除它们.例如
indexes_to_drop = []对于 df.index 中的 i:....如果{在此处做出决定}:indexs_to_drop.append(i)....df.drop(df.index[indexes_to_drop], 就地=真)
I have a dataframe df
Name dist
aaaa 10
bbbb 11
cccc 41
dddd 77
I want to delete rows which have dist less than 10 to the next row. The expexted output is
Name dist
aaaa 10
cccc 41
dddd 77
To do this I used the following code
>>> for idx,row in df.iterrows():
... if idx < df.shape[0]-1:
... if ((df.ix[idx+1,'dist_to_TSS']-df.ix[idx+1,'dist_to_TSS'])<10):
... df.drop(row)
...
But I get errors. Can you help?
解决方案
If your criteria for deciding which rows you want to drop is a little trickier, e.g. relating to values in the previous/next row then an easy way is to simply build up a list of indexes of rows that you want to delete and then delete them all in one go at the end. e.g.
indexes_to_drop = []
for i in df.index:
....
if {make your decision here}:
indexes_to_drop.append(i)
....
df.drop(df.index[indexes_to_drop], inplace=True )
这篇关于在遍历 Pandas 数据帧时删除一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文