根据列值删除Pandas中的DataFrame行

我有以下的DataFrame:

daysago line_race rating rw wrating line_date 2007-03-31 62 11 56 1.000000 56.000000 2007-03-10 83 11 67 1.000000 67.000000 2007-02-10 111 9 66 1.000000 66.000000 2007-01-13 139 10 83 0.880678 73.096278 2006-12-23 160 10 88 0.793033 69.786942 2006-11-09 204 9 52 0.636655 33.106077 2006-10-22 222 8 66 0.581946 38.408408 2006-09-29 245 9 70 0.518825 36.317752 2006-09-16 258 11 68 0.486226 33.063381 2006-08-30 275 8 72 0.446667 32.160051 2006-02-11 475 5 65 0.164591 10.698423 2006-01-13 504 0 70 0.142409 9.968634 2006-01-02 515 0 64 0.134800 8.627219 2005-12-06 542 0 70 0.117803 8.246238 2005-11-29 549 0 70 0.113758 7.963072 2005-11-22 556 0 -1 0.109852 -0.109852 2005-11-01 577 0 -1 0.098919 -0.098919 2005-10-20 589 0 -1 0.093168 -0.093168 2005-09-27 612 0 -1 0.083063 -0.083063 2005-09-07 632 0 -1 0.075171 -0.075171 2005-06-12 719 0 69 0.048690 3.359623 2005-05-29 733 0 -1 0.045404 -0.045404 2005-05-02 760 0 -1 0.039679 -0.039679 2005-04-02 790 0 -1 0.034160 -0.034160 2005-03-13 810 0 -1 0.030915 -0.030915 2004-11-09 934 0 -1 0.016647 -0.016647 

我需要删除line_race等于0的行。 什么是最有效的方法来做到这一点?

如果我理解正确,应该像下面这样简单:

 df = df[df.line_race != 0] 

但是对于任何未来的绕过者,你可以提到df = df[df.line_race != 0]在尝试筛选None / missing值时不会做任何事情。

工作:

 df = df[df.line_race != 0] 

什么都不做:

 df = df[df.line_race != None] 

工作:

 df = df[df.line_race.notnull()] 

最好的方法是使用布尔掩码:

 In [56]: df Out[56]: line_date daysago line_race rating raw wrating 0 2007-03-31 62 11 56 1.000 56.000 1 2007-03-10 83 11 67 1.000 67.000 2 2007-02-10 111 9 66 1.000 66.000 3 2007-01-13 139 10 83 0.881 73.096 4 2006-12-23 160 10 88 0.793 69.787 5 2006-11-09 204 9 52 0.637 33.106 6 2006-10-22 222 8 66 0.582 38.408 7 2006-09-29 245 9 70 0.519 36.318 8 2006-09-16 258 11 68 0.486 33.063 9 2006-08-30 275 8 72 0.447 32.160 10 2006-02-11 475 5 65 0.165 10.698 11 2006-01-13 504 0 70 0.142 9.969 12 2006-01-02 515 0 64 0.135 8.627 13 2005-12-06 542 0 70 0.118 8.246 14 2005-11-29 549 0 70 0.114 7.963 15 2005-11-22 556 0 -1 0.110 -0.110 16 2005-11-01 577 0 -1 0.099 -0.099 17 2005-10-20 589 0 -1 0.093 -0.093 18 2005-09-27 612 0 -1 0.083 -0.083 19 2005-09-07 632 0 -1 0.075 -0.075 20 2005-06-12 719 0 69 0.049 3.360 21 2005-05-29 733 0 -1 0.045 -0.045 22 2005-05-02 760 0 -1 0.040 -0.040 23 2005-04-02 790 0 -1 0.034 -0.034 24 2005-03-13 810 0 -1 0.031 -0.031 25 2004-11-09 934 0 -1 0.017 -0.017 In [57]: df[df.line_race != 0] Out[57]: line_date daysago line_race rating raw wrating 0 2007-03-31 62 11 56 1.000 56.000 1 2007-03-10 83 11 67 1.000 67.000 2 2007-02-10 111 9 66 1.000 66.000 3 2007-01-13 139 10 83 0.881 73.096 4 2006-12-23 160 10 88 0.793 69.787 5 2006-11-09 204 9 52 0.637 33.106 6 2006-10-22 222 8 66 0.582 38.408 7 2006-09-29 245 9 70 0.519 36.318 8 2006-09-16 258 11 68 0.486 33.063 9 2006-08-30 275 8 72 0.447 32.160 10 2006-02-11 475 5 65 0.165 10.698 

更新:现在,大pandas0.13出来了,另一种方法是df.query('line_race != 0')

给定的答案是正确的,因为上面说的人可以使用df.query('line_race != 0') ,这取决于你的问题要快得多。 强烈推荐。