【发布时间】:2015-08-10 16:07:04
【问题描述】:
我有数据框:
import pandas as pd
id = [0,0,0,0,0,1,1,1,1,1]
value = [1,3,2,5,4,4,3,2,1,5]
test = pd.DataFrame(zip(id, value), columns = ['id', 'value'])
我想要一个扩展的 apply 函数来识别我们是否达到给定 id 的新最大值。生成的数据框应如下所示:
id value new_max
0 0 1 1
1 0 3 1
2 0 2 0
3 0 5 1
4 0 4 0
5 1 4 1
6 1 3 0
7 1 2 0
8 1 1 0
9 1 5 1
我似乎无法将两列传递给扩展应用函数。
我尝试创建一个新列:
test['id_value'] = zip(test['id'], test['value'])
然后传递元组:
def new_max(x):
v, w = list(zip(*x)[0]), list(zip(*x)[1])
last_id = v[-1]
last_value = w[-1]
if any(j >= last_value for j in [w[i] for i, k in enumerate(v[0:-1]) if k == last_id]):
return 0
else:
return 1
test['new_max'] = test['id_value'].apply(lambda x: pd.expanding_apply(x, new_max))
但我得到了错误:
AttributeError: 'tuple' object has no attribute 'dtype'
任何建议将不胜感激!
一种绕过两列的解决方案 (虽然通过两列知道如何做到这一点仍然很好)
def new_max2(x):
if any(j >= x[-1] for j in x[0:-1]):
return 0
else:
return 1
test.groupby('id')['value'].apply(lambda x: pd.expanding_apply(x, new_max2))
【问题讨论】:
-
如果你有一个新的最大值,后面紧跟着重复相同的值,例如[5,1,2,3,6,6],您希望两个 6 都有 1 还是只有第一个? (我假设您只想要第一个,因为它是设置新最大值的那个。)
-
@DSM(只有第一个,我写错了代码,所以我会编辑)感谢您的回复。我只是想通了,其实。绕过两列的传递,但如果有人知道如何做到这一点,它可能对其他有这个问题的人有所帮助。我会在上面发布我的特定解决方案和问题。