首页 > 解决方案 > 使用“if in”时元素现有标识错误

问题描述

这是我的代码:

df1 = pd.DataFrame({'a': [1,2,3,1,2,3,3],'b':[1,2,3,1,2,3,3],'type':[1,0,1,0,1,0,1]})
def add_buy_label(group):
    behavior_type = group.type.astype(int)
    if 1 in group['type']:
        group['buy_label'] = 1
    else:
        group['buy_label'] = 0

    return group[['a', 'b', 'type','buy_label']]

上面的功能是让所有ab项的buy_label为1,只要组中存在一个(type = 1),但是,之后的结果

df1.groupby(['a','b'],as_index = False).apply(add_buy_label)

    a  b  type  buy_label
0  1  1     1          0
1  2  2     0          1
2  3  3     1          0
3  1  1     0          0
4  2  2     1          1
5  3  3     0          0
6  3  3     1          0

很明显,3的行是错误的,因为(a=3,b=3)的组中存在type = 1,但相应的buy_label为0。

我该如何解决?

标签: pythonpandasif-statementpandas-groupby

解决方案


有问题in测试索引值,而不是列值。

#sorting for better seen groups 
df1 = df1.sort_values(['a','b'])
df2 = df1.groupby(['a','b'],as_index = False).apply(add_buy_label)
print (df2)
   a  b  type  buy_label
0  1  1     1          0
3  1  1     0          0
1  2  2     0          1 <- return 1 only because index == 1 per group (2,2)
4  2  2     1          1
2  3  3     1          0
5  3  3     0          0
6  3  3     1          0

所以需要通过1with anyfor 检查至少一项True

if group['type'].eq(1).any():
#what is same as
if (group['type'] == 1).any():

推荐阅读