Pandas drop function not working in a for loop?

后端 未结 2 989
野趣味
野趣味 2021-01-07 09:25

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 n

相关标签:
2条回答
  • 2021-01-07 09:58

    This should work

    for i in range(len(bb_db)):
        if 'Barry Bonds' in bb_db['player_names'][i]:
            bb_db = bb_db.drop(bb_db.index[i])
            # or this works too..
            # bb_db.drop(bb_db.index[i], inplace=True)
            print (i)
    
    0 讨论(0)
  • 2021-01-07 10:02

    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')]
    
    0 讨论(0)
提交回复
热议问题