pandas 掉落功能无法在for循环中使用? [英] Pandas drop function not working in a for loop?

查看:78
本文介绍了 pandas 掉落功能无法在for循环中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部! 我对此感到非常困惑,因为我的一生无法弄清错误. 我试图遍历数据帧中的所有字符串,并删除不包含字符串"Barry Bonds"的字符串.

到目前为止,我已经能够按其索引删除行:

bb_db.drop(bb_db.index[1])

这可以成功地删除该索引处的行,但是当我将其放入此for循环中时:

for i in range(len(bb_db)):
    if 'Barry Bonds' in bb_db['player_names'][i]:
        bb_db.drop(bb_db.index[i])
        print (i)

即使i变量在if语句为true的情况下打印出大量索引,我仍会获得整个数据帧.

谢谢!

解决方案

drop不会更改您当前的DataFrame,除非您要求使用inplace=True对其进行更改.

话虽如此,for循环几乎肯定不是这里最简单的方法.为什么不使用列上的str访问器(即使用 str.contains

bb_db[~bb_db.player_names.str.contains('Barry Bonds')]

all! I am pretty confused by this and for the life of me cannot figure out the error. I am trying to go through all the strings in a data frame and remove the ones that do not contain the string 'Barry Bonds'.

So far I have managed to be able to drop rows by their index:

bb_db.drop(bb_db.index[1])

This is successful at dropping the row at that index, however when I throw it into this for loop:

for i in range(len(bb_db)):
    if 'Barry Bonds' in bb_db['player_names'][i]:
        bb_db.drop(bb_db.index[i])
        print (i)

I get the entire dataframe, even though the i variable prints out a ton of indexes with the if statement as being true.

Thank you!

解决方案

drop doesn't mutate your current DataFrame unless you ask it to, with inplace=True.

With that being said, a for loop is almost certainly not the easiest approach here. Why not just boolean indexing with the str accessor on your column, i.e. with str.contains

bb_db[~bb_db.player_names.str.contains('Barry Bonds')]

这篇关于 pandas 掉落功能无法在for循环中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆