如何在转换函数中包含两个lambda运算? [英] How to include two lambda operations in transform function?
问题描述
我有一个如下所示的数据帧
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]
})
我想应用几个逻辑( val
列上的 logic_1
和<在 date
列上输入了code> logic_2 )。请在逻辑下面找到
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))
向SO用户提供帮助的信用带有逻辑
credit to SO users for helping me with logic
这是我在下面尝试的
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:''})
如何使 logic_1
和 logic_2
都成为一个逻辑语句的一部分?可能吗我可能也有两种以上的逻辑。不必为每个逻辑写一行,而是可以在一个逻辑语句中将所有逻辑耦合在一起。
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.
我希望我的输出是当
满意 logic_1
和 logic_2都用
列 1
填充label
I expect my output to be with label
column being filled with 1
when both logic_1
and logic_2
are satisfied
推荐答案
您有几件要解决的问题
首先,在 logic_2
中,您有 lambda x
,但使用 y
,因此,您必须进行如下更改
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'})
注意:您的逻辑生成所有错误的
值。因此,如果 False
映射到1,而不是 True
Note: You logic produces all False
values. So, you will get 1's if False
is mapped to 1, not True
这篇关于如何在转换函数中包含两个lambda运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!