【问题标题】:Find similar rows and subtract a particular column value in Pandas Dataframe在 Pandas Dataframe 中查找相似的行并减去特定的列值
【发布时间】:2020-03-08 01:01:21
【问题描述】:

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

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

所以,

     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 到达那里。 问题和数据有点复杂,所以我可以在这里发布代码。

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

谢谢, 抢

【问题讨论】:

  • 请提供您希望表格处理后的样子的样本。阅读this 文章,了解如何发布一个好的可重现问题。

标签: python pandas dataframe data-wrangling


【解决方案1】:

所以我不确定您希望结果的确切格式,所以我制作了一个字典,其中键是给定行的索引,值是正好相差 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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    • 1970-01-01
    • 2022-12-14
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多