Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter shift +/- 1 day in Pandas?

Tags:

python

pandas

Suppose I have timeseries data. How to filter data that only occurs in 1 days different?

Suppose the data is

date         name
2015-04-03    A
2015-04-04    A
2015-04-05    A
2015-04-03    B

What I want to do is something like

df[df.shift(1).contains(df.name) or df.shift(-1).contains(df.name)]

that would give me

date         name
2015-04-03    A
2015-04-04    A
2015-04-05    A

How to do this in pandas?

like image 207
Napitupulu Jon Avatar asked Nov 09 '22 08:11

Napitupulu Jon


1 Answers

You want to wrap your conditions in parentheses and use the bitwise | instead of or:

In [83]:
df[(df['name'].shift(1) == df['name']) | (df['name'].shift(-1) == df['name']) ]

Out[83]:
        date name
0 2015-04-03    A
1 2015-04-04    A
2 2015-04-05    A
like image 192
EdChum Avatar answered Nov 14 '22 23:11

EdChum