python - 如何根据列值python标记多个数据框行
问题描述
我有一个数据框如下:
ID Reviews Sorted pairwise scores
A This is great 0 [(0, 1)] [0.26386763883335373]
A works well 1 [] []
B can this be changed 0 [(0, 1), (0, 2)] [0.1179287227608669, 0.36815020951152794]
B how to perform that 1 [(1, 2)] [0.03299057711398918]
B summarize it 2 [] []
排序将是 ID 中重复项的顺序。Pairwise 是按 ID 分组的成对组合。我通过使用成对组合得到了分数列。现在我需要创建一个标志列,如果分数 > 0.15,则基于成对列标记“是”。例如,当按 ID 分组时,值 B 的分数 > 0.15 为 0.36,当我们查看成对列 (0,2) 时,即 0 和 2 行应标记为“是”。
我想要的输出是:
ID Reviews Sorted pairwise scores Flag
A This is great 0 [(0, 1)] [0.26386763883335373] yes
A works well 1 [] [] yes
B can this be changed 0 [(0, 1), (0, 2)] [0.1179287227608669, 0.36815020951152794] yes
B how to perform that 1 [(1, 2)] [0.03299057711398918] No
B summarize it 2 [] [] yes
我尝试使用 np.where 来获取分数,但对我不起作用。
任何人都可以建议解决方法或任何想法吗?提前致谢!
解决方案
我们做explode
,然后merge
它回来
s=df.scores.explode()
s=df.set_index('ID').pairwise.explode()[(s>0.15).values].explode()
df=df.merge(s.to_frame('Sorted').reset_index().assign(flag='Yes'),how='left')
df.flag.fillna('No',inplace=True)
df
scores pairwise Sorted ID flag
0 [0.26386763883335373] [(0, 1)] 0 A Yes
1 [] [] 1 A Yes
2 [0.1179287227608669, 0.36815020951152794] [(0, 1), (0, 2)] 0 B Yes
3 [0.03299057711398918] [(1, 2)] 1 B No
4 [] [] 2 B Yes
推荐阅读
- reactjs - 每次单击模式弹出按钮时,Reactjs 仅显示第一条记录
- ocaml - 你如何在 ocaml 的编译器中使用 gcc 的 ar 实用程序?
- java - 如何将接口作为泛型类型传递并将其用作注释?
- javascript - 我如何在两个 Ajax 请求之间切换
- mysql - 有没有更有效的方法使用 mysql 来获取 sql 结果中给定列的列表?
- upload - 如何使用 Bulletproof php 上传 blob
- caching - 如何在 GitLab CI 中有一个“每个 package.json 的缓存”文件?
- ios - 处理 URLSession 时总是需要 [Weak self] 吗?
- javascript - 当鼠标已经在元素上并且已经移动时,如何启用可拖动?
- python - 不能在 .format() 字符串中直接使用 randint() 吗?