How to include two lambda operations in transform function?

自古美人都是妖i 提交于 2019-12-11 16:55:40

问题


I have a dataframe like as given below

df = pd.DataFrame({
'date' :['2173-04-03 12:35:00','2173-04-03 17:00:00','2173-04-03 20:00:00','2173-04-04 11:00:00','2173-04-04 12:00:00','2173-04-04 11:30:00','2173-04-04 16:00:00','2173-04-04 22:00:00','2173-04-05 04:00:00'],
'subject_id':[1,1,1,1,1,1,1,1,1],
'val' :[5,5,5,10,10,5,5,8,8]
 })

I would like to apply couple of logic (logic_1 on val column and logic_2 on date column) to the code. Please find below the logic

logic_1 = lambda x: (x.shift(2).ge(x.shift(1))) & (x.ge(x.shift(2).add(3))) & (x.eq(x.shift(-1)))
logic_2 = lambda y: (y.shift(1).ge(1)) & (y.shift(2).ge(2)) & (y.shift(-1).ge(1)) 

credit to SO users for helping me with logic

This is what I tried below

   df['label'] = ''
   df['date'] = pd.to_datetime(df['date'])
   df['tdiff'] = df['date'].shift(-1) - df['date']
   df['tdiff'] = df['tdiff'].dt.total_seconds()/3600
   df['lo_1'] = df.groupby('subject_id')['val'].transform(logic_1).map({True:'1',False:''})
   df['lo_2'] = df.groupby('subject_id')['tdiff'].transform(logic_2).map({True:'1',False:''}) 

How can I make both the logic_1 and logic_2 be part of one logic statement? Is it even possible? I might have more than 2 logics as well. Instead of writing one line for each logic, is it possible to couple all logics together in one logic statement.

I expect my output to be with label column being filled with 1 when both logic_1 and logic_2 are satisfied


回答1:


You have a few things to fix First, in logic_2, you have lambda x but use y, so, you got to change that as below

logic_2 = lambda y: (y.shift(1).ge(1)) & (y.shift(2).ge(2)) & (y.shift(-1).ge(1))

Then you can use the logic's together as below' No need to create a blank column label. You can create the '`label' column directly as below.

df['label'] = ((df.groupby('subject_id')['val'].transform(logic_1))
           & (df.groupby('subject_id')['tdiff'].transform(logic_2))).map({True:'0',False:'1'})

Note: You logic produces all False values. So, you will get 1's if False is mapped to 1, not True



来源:https://stackoverflow.com/questions/57695288/how-to-include-two-lambda-operations-in-transform-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!