pandas dataframe根据列中的值删除后续行

时间:2015-09-16 18:37:40

标签: python pandas dataframe

简单的问题但我无法找到任何相关内容。我有以下数据框,并希望完成以下任务:

我们的数据框中Roll = 1,我想删除下一行,只删除那一行。请记住,Roll的许多行将为0,但只需要删除少数几行,其中前一行为Roll = 1

Date    Close    Open    Roll
1       500      499     0
2       502      502     0
3       500      499     0
4       500      499     1
5       501      502     0 (delete this row)
6       506      506     0
7       509      508     0

1 个答案:

答案 0 :(得分:3)

使用shift创建一个布尔掩码,测试前一行是否包含1:

?- time(money_puzzle([S,E,N,D],[M,O,R,E],[M,O,N,E,Y])).
% 38,710 inferences, 0.016 CPU in 0.016 seconds (100% CPU, 2356481 Lips)
S = 9,
E = 5,
N = 6,
D = 7,
M = 1,
O = 0,
R = 8,
Y = 2 ;
% 15,287 inferences, 0.009 CPU in 0.009 seconds (99% CPU, 1685686 Lips)
false.

?-  time(money_puzzle([D,O,N,A,L,D],[G,E,R,A,L,D],[R,O,B,E,R,T])).
% 14,526 inferences, 0.008 CPU in 0.008 seconds (99% CPU, 1870213 Lips)
D = 5,
O = 2,
N = 6,
A = 4,
L = 8,
G = 1,
E = 9,
R = 7,
B = 3,
T = 0 ;
% 13,788 inferences, 0.009 CPU in 0.009 seconds (99% CPU, 1486159 Lips)
false.

布尔掩码如下所示:

In [24]:
df[df['Roll'].shift() != 1]

Out[24]:
   Date  Close  Open  Roll
0     1    500   499     0
1     2    502   502     0
2     3    500   499     0
3     4    500   499     1
5     6    506   506     0
6     7    509   508     0