代码之家  ›  专栏  ›  技术社区  ›  watchtower

大熊猫两个表的行差异

  •  1
  • watchtower  · 技术社区  · 8 年前

    我正在使用 pandas 为了递增地找出新元素,即对于每一行,我要查看列表中的值以前是否见过。如果他们是,我们将忽略他们。如果没有,我们将选择他们。

    row.iterrows() ,但我有>1百万行,所以我相信矢量化了 apply

    下面是示例数据和代码。运行此代码后,将获得预期的输出:

    from numpy import nan as NA
    import collections
    
    df = pd.DataFrame({'ID':['A','B','C','A','B','A','A','A','D','E','E','E'],
                       'Value': [1,2,3,4,3,5,2,3,7,2,3,9]})
    #wrap all elements by group in a list
    Changed_df=df.groupby('ID')['Value'].apply(list).reset_index() 
    Changed_df=Changed_df.rename(columns={'Value' : 'Elements'})
    Changed_df=Changed_df.reset_index(drop=True)
    
    
    
    def flatten(l):
        for el in l:
            if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
                yield from flatten(el)
            else:
                yield el
    
    Changed_df["Elements_s"]=Changed_df['Elements'].shift()
    
    #attempt 1: For loop
    Changed_df["Diff"]=NA
    Changed_df["count"]=0
    Elements_so_far = []
    
    #replace NA with empty list in columns that will go through list operations
    for col in ["Elements","Elements_s","Diff"]:
        Changed_df[col] = Changed_df[col].apply(lambda d: d if isinstance(d, list) else [])
    
    for idx,row in Changed_df.iterrows():
        diff = list(set(row['Elements']) - set(Elements_so_far))
        Changed_df.at[idx, "Diff"] = diff
        Elements_so_far.append(row['Elements'])
        Elements_so_far = flatten(Elements_so_far)
        Elements_so_far = list(set(Elements_so_far)) #keep unique elements
        Changed_df.loc[idx,"count"]=diff.__len__()
    

    守则评注:

      • Elements_s 它保存了移位的值。效率低下的另一个原因是 for 循环行。
    • Elements_so_far 跟踪我们为每一行发现的所有元素。如果有新元素出现,我们就把它算进去 Diff 列。
    • 我们还记录了在地球上发现的新元素的长度 count 列。

    如果有专家能帮我一个矢量化版本的代码,我将不胜感激。


    我确实尝试过矢量化的版本,但我不能走得太远。

    #attempt 2:
    Changed_df.apply(lambda x: [i for i in x['Elements'] if i in x['Elements_s']], axis=1)
    

    我的灵感来自 How to compare two columns both with list of strings and create a new column with unique items? 但我做不到。链接的SO线程在列之间执行行差异。

    2 回复  |  直到 8 年前
        1
  •  2
  •   AChampion    8 年前

    你可以用 sort 然后用numpy得到 unique 索引,然后构建分组,例如:

    In []:
    df = df.sort_values(by='ID').reset_index(drop=True)
    _, i = np.unique(df.Value.values, return_index=True)
    df.iloc[i].groupby(df.ID).Value.apply(list)
    
    Out[]:
    ID
    A    [1, 2, 3, 4, 5]
    D                [7]
    E                [9]
    Name: Value, dtype: object
    

    或接近当前输出:

    In []:
    df = df.sort_values(by='ID').reset_index(drop=True)
    _, i = np.unique(df.Value.values, return_index=True)
    s1 = df.groupby(df.ID).Value.apply(list).rename('Elements')
    s2 = df.iloc[i].groupby(df.ID).Value.apply(list).rename('Diff').reindex(s1.index, fill_value=[])
    
    pd.concat([s1, s2, s2.apply(len).rename('Count')], axis=1)
    
    Out[]:
               Elements             Diff  Count
    ID
    A   [1, 4, 5, 2, 3]  [1, 2, 3, 4, 5]      5
    B            [2, 3]               []      0
    C               [3]               []      0
    D               [7]              [7]      1
    E         [2, 3, 9]              [9]      1
    
        2
  •  1
  •   Abhi    8 年前

    drop duplicates 和 groupby

    # Groupby and apply list func.
    df1 = df.groupby('ID')['Value'].apply(list).to_frame('Elements')
    
    # Sort values , drop duplicates by Value column then use groupby.
    df1['Diff'] = df.sort_values(['ID','Value']).drop_duplicates('Value').groupby('ID')['Value'].apply(list)
    
    # Use str.len for count.
    df1['Count'] = df1['Diff'].str.len().fillna(0).astype(int)
    
    # To fill NaN with empty list
    df1['Diff'] = df1.Diff.apply(lambda x: x if type(x)==list else []) 
    
    
               Elements             Diff   Count
    ID               
    A   [1, 4, 5, 2, 3]  [1, 2, 3, 4, 5]     5
    B            [2, 3]               []     0
    C               [3]               []     0
    D               [7]              [7]     1
    E         [2, 3, 9]              [9]     1