python - Pandas 数据帧行的特定复杂过滤
问题描述
数据有很多列,但有问题的列如下:
MR Version
GB1 Package
GB5 Package
GB9 3.5
GB5 3.3
GB1 Package
GB9 1.5
GB359 9.1
GB1 Package
GB99 5.5
...
MR(模型)名称重复,并且Package
版本列也在重复。我需要首先使用 Version == 访问所有行Package
,
- 然后以他们的 MR 型号名称为例
GB5
- 然后找到具有相同 MR 模型名称的所有其他行和
- 最后检查那些其他行(具有相同的 MR 模型名称)是否具有与 Package(!= Package)不同的 Version 列的值。有的我需要归类为好,没有的我需要归类为坏。
例如,从上面的示例数据中,MR 模型GB5
同时具有 Package 和非 Package 单元格,因此该模型是好的,而模型 GB1 在版本列中只有 Package 值,因此它是坏的。
对于版本列中只有整数值的 MR,例如GB9
我们在此任务中不关心。
通常这些条目彼此相邻,并且通常有两个模型,所以我开发了一个循环,通过从数据框中选择每两行来成功解决下面的问题,但现在我发现在某些情况下这些条目不是彼此相邻,所以我需要一个更好的解决方案来逃避我。非常感谢任何帮助,谢谢大家。在我下面的代码中,MR 被 Author 替换,但这并不重要。
good_aut = []
bad_aut = []
for i, g in merged_df.groupby(merged_df.index // 2): # takes every two rows
if g.iloc[0]['Version'] == 'Package': # if row 1 is a package citation
if g.iloc[0]['Author'] == g.iloc[1]['Author']: # check if row 1 and 2 authors match
if g.iloc[1]['Version'] != 'Package': # finally check if row 2 citation is not package, hence it is GAP citation
print(g)
good_aut.append(g.iloc[0]['Author']) # if all conditions are met we add this author to the good list, once for every occurence
else:
bad_aut.append(g.iloc[0]['Author'])
else:
bad_aut.append(g.iloc[0]['Author'])
解决方案
不清楚。除了其他值之外,您还期望Package
存在吗?
如果是
您可以分组MR
并检查是否Package
与其他值一起存在:
def good_or_bad(s):
s=set(s)
if 'Package' in s and len(s.difference(['Package']))>0:
return 'good'
return 'bad'
df.groupby('MR')['Version'].apply(good_or_bad)
输出:
MR
GB1 bad
GB359 bad
GB5 good
GB9 bad
GB99 bad
Name: Version, dtype: object
如果不
您可以分组MR
并检查是否存在其他值Package
:
(df.groupby('MR')['Version']
.apply(lambda s: len(set(s).difference(['Package']))>0)
.map({True: 'good', False: 'bad'})
)
输出:
MR
GB1 bad
GB359 good
GB5 good
GB9 good
GB99 good
Name: Version, dtype: object
我想要所有三种可能性
def good_or_bad(s):
s=set(s)
if len(s.difference(['Package']))>0:
if 'Package' in s:
return 'good'
return 'other'
return 'bad'
df.groupby('MR')['Version'].apply(good_or_bad)
输出:
MR
GB1 bad
GB359 other
GB5 good
GB9 other
GB99 other
Name: Version, dtype: object
推荐阅读
- r - 曲线函数不画函数?
- javascript - 无法使用替换来重命名单元格
- angular - 来自 api 响应的 Angular 反应表单自定义异步验证
- android - 正确处理禁用/只读文本框以实现可访问性
- ios - 动态大小嵌套的 UIStackView
- c# - 有没有一种在 Visual Studio 之外编辑代码分析规则集的好方法
- java - Impala 单个插入语句创建多个文件
- ios - iOS 12 - oneTimeCode OTP 委托
- javascript - 淘汰赛点击绑定不会在点击时触发
- java - DataVirt 错误“MSC000001:无法启动服务 jboss.web.deployment.default-host 服务 jboss.web.development.default-host 中的启动异常。/”