Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas: filter group by multiple conditions?

I have a data frame that looks like this:

df = pd.DataFrame([
  {'id': 123, 'date': '2016-01-01', 'is_local': True },
  {'id': 123, 'date': '2017-01-01', 'is_local': False },
  {'id': 124, 'date': '2016-01-01', 'is_local': True },
  {'id': 124, 'date': '2017-01-01', 'is_local': True }
])
df.date = df.date.astype('datetime64[ns]')

I want to get a list of all the IDs for which is_local was True at the start of 2016, but False at the start of 2017. I've started by grouping by ID:

gp = df.groupby('id')

Then I've tried this just to filter by the second of these conditions (as a way of getting started), but it's returning all the groups:

gp.apply(lambda x: ~x.is_local & (x.date > '2016-12-31'))

How can I filter in the way I need?

like image 805
Richard Avatar asked May 05 '17 08:05

Richard


3 Answers

d1 = df.set_index(['id', 'date']).is_local.unstack()
d1.index[d1['2016-01-01'] & ~d1['2017-01-01']].tolist()

[123]
like image 97
piRSquared Avatar answered Oct 23 '22 12:10

piRSquared


Another way of doing this is through pivoting:

In [24]: ids_by_dates = df.pivot(index='id', columns='date',values='is_local')

In [25]: ids_by_dates['2016-01-01'] & ~ids_by_dates['2017-01-01']
Out[25]: 
id
123     True
124    False
like image 21
Ami Tavory Avatar answered Oct 23 '22 12:10

Ami Tavory


You can try using the datetime module from datetime library and pass multiple conditions for the dataframe

from datetime import datetime
df = pd.DataFrame([
  {'id': 123, 'date': '2016-01-01', 'is_local': True },
  {'id': 123, 'date': '2017-01-01', 'is_local': False },
  {'id': 124, 'date': '2016-01-01', 'is_local': True },
  {'id': 124, 'date': '2017-01-01', 'is_local': True }
])
df.date = df.date.astype('datetime64[ns]')

Use multiple conditions for slicing out the required dataframe

a = df[(df.is_local==True) & (df.date<datetime(2016,12,31) & (df.date>datetime(2015,12,31))]
b = df[(df.is_local==False) & (df.date<datetime(2017,12,31)) & (df.date>datetime(2016,12,31))]

Use pandas concatenate later

final_df = pd.concat((a,b))

will output you rows 1 and 2

    date        id  is_local
2   2016-01-01  124 True
1   2017-01-01  123 False

In single line as follows

final_df = pd.concat((df[(df.is_local==True) & (df.date<datetime(2016,12,31) & (df.date>datetime(2015,12,31))], df[(df.is_local==False) & (df.date<datetime(2017,12,31)) & (df.date>datetime(2016,12,31))]))
like image 41
Raja Sattiraju Avatar answered Oct 23 '22 10:10

Raja Sattiraju