python - 使用“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。
我该如何解决?
解决方案
有问题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
所以需要通过1
with any
for 检查至少一项True
:
if group['type'].eq(1).any():
#what is same as
if (group['type'] == 1).any():
推荐阅读
- r - 在 R 中加入不同 SpatialPolygonsDataFrame 对象的问题
- angular - 如何将 Mat-Dialog 中的数据转换为类对象
- sip - 通过 UDP 建立的 SIP 对话 - 通过 TCP 发送大型 SIP 请求后的传输是什么?
- puppeteer - 如何在 puppeteer 中测试元素是否可点击?
- java - 带有lombok抛出错误的groovy-eclipse-compiler
- python - 如何在python中将多个数据源转换为预定义的数据结构?
- python - 更改使用 PyPDF2 创建的矩形链接轮廓的颜色
- python - 加载 txt 并转换为 npy 保持相同的形状
- postgresql - 如何使用带有 pg_trgm 的 2 个表使用 Postgres 全文搜索功能对结果进行排序
- video - 如何使用选定的音频流将视频转换为 hls?