首页 > 解决方案 > 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同时具有 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'])
        

标签: pythonpandasdataframefor-loopjupyter-notebook

解决方案


不清楚。除了其他值之外,您还期望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

推荐阅读