首页 > 解决方案 > 在 Pandas Dataframe 中查找相似的行并减去特定的列值

问题描述

我知道这里有类似的问题和解决方案,但我似乎没有找到确切的解决方案。

想要找到与“除了一个”列相似的行。

所以,

     ColumnA     ColumnB     ColumnC    ColumnD  ColumnE  
1      John        Texas       USA        115       5
2      Mike        Florida     USA        66        1
3      John        Texas       USA        115       4
4      Justin      NewYork     USA        22        11

所以我试图得到的逻辑是:

for every entry in the dataframe:
       if there exists "another" entry with all Columns similar, apart from ColumnE
        AND
       the value of ColumnE in First entry found "MINUS" the value of ColumnE in second entry found is "LESS" than "1":
                   Then append the entry to a new DataFrame

到目前为止,我已经使用 df.loc 和 df.duplicated 到达某个地方。问题和数据有点复杂,所以我可以在这里发布代码。

对此的任何帮助将不胜感激。

谢谢,罗伯

标签: pythonpandasdataframedata-wrangling

解决方案


所以我不确定你想要你的结果是什么格式,所以我制作了一个字典,其中键是给定行的索引,值是正好相差 1 个条目的行的索引列表......

def ndif(a,b):
    d = 0
    for x,y in zip(a,b):
            if x!=y:
                    d+=1
    return(d)

d = pd.DataFrame([[1,2,3],[1,2,4],[3,2,4],[3,0,4],[5,0,3]])

just1 = {}

for k in d.index:
    just1[k] = [k[0] for k in d.apply(ndif,args=[d.iloc[k]],axis=1).items() if k[1]==1]

推荐阅读