【问题标题】:Extension of Comparing columns of dataframes and returning the difference扩展比较数据框的列并返回差异
【发布时间】:2019-04-01 13:52:05
【问题描述】:

这是我上一个问题的延伸:Comparing columns of dataframes and returning the difference

在比较了我收集的 37 个数据帧中所有数据帧的列后,我发现有些数据帧的列相似,而有些则不同。所以现在需要比较这些不同的数据帧并返回差异。此步骤应继续进行,直到所有数据帧都被分类为两组,即具有相似列的数据帧进入一组,不同列的数据帧进入第二组。

例如:


df = [None] * 6

df[0] = pd.DataFrame({'a':[1,2,3],'b':[3,4,5], 'c':[7,8,3], 'd':[1,5,3]})
df[1] = pd.DataFrame({'a':[1,2,3],'b':[3,4,5], 'c':[7,8,3], 'd':[1,5,3]})
df[2] = pd.DataFrame({'a':[1,2,3],'b':[3,4,5], 'x':[7,8,3], 'y':[1,5,3]})
df[3] = pd.DataFrame({'a':[1,2,3],'b':[3,4,5], 'c':[7,8,3], 'd':[1,5,3]})
df[4] = pd.DataFrame({'a':[1,2,3],'b':[3,4,5], 'x':[7,8,3], 'z':[1,5,3]})
df[5] = pd.DataFrame({'a':[1,2,3],'b':[3,4,5], 'x':[7,8,3], 'y':[1,5,3]})

# code to group the dataframes into similar and different cols groups

nsame = []
same = []
    for i in range(0, len(df)):
        for j in range(i+1, len(df)):
            if not (df[i].columns.equals(df[j].columns)):
                nsame.append(j)
            else:
                same.append(i)

当我为同一组(相同)打印上述代码时,输​​出为:

print(same)
[0, 0, 1, 2]

期望的输出:

print(same)
[0, 1, 3]

也许我需要一个递归函数来将所有相似的列分组到一个组中,并将所有不同的列数据框分组到一个不同的组中。然而,棘手的部分是可以有两个以上的组。例如,在上面的代码中,有3组:

Group1: df[0], df[1], df[3]
Group2: df[2], df[5]
Group3: df[4]

有人可以帮忙吗?

【问题讨论】:

    标签: pandas python-2.7 dataframe


    【解决方案1】:

    这是一种方法

    s=pd.Series([','.join(x) for x in df])
    s.groupby(s).groups # the out put here already make the dfs into groups 
    Out[695]: 
    {'a,b,c,d': Int64Index([0, 1, 3], dtype='int64'),
     'a,b,x,y': Int64Index([2, 5], dtype='int64'),
     'a,b,x,z': Int64Index([4], dtype='int64')}
    

    [y.index.tolist() for x , y in s.groupby(s)]
    Out[699]: [[0, 1, 3], [2, 5], [4]]
    

    【讨论】:

    • 你的答案有效,但由于我有 37 个数据帧,每个数据帧有大约 100-120 列,我正在考虑一个更简单的输出解决方案,我可以将索引作为组而不是列名或类型。有没有办法得到这个?
    • 编辑你的最后一行代码: pd.DataFrame([y.index.tolist() for x , y in s.groupby(s)]).T.fillna('').astype (int, errors='ignore') 效果很好!
    【解决方案2】:

    将所有列名作为不同的熊猫数据框传递不是更容易吗,即:

    a - b - c - d
    a - b - c - d
    a - b - x - y
    ...
    

    只需对列进行简单的分组

    groupby res 上的 count() 系列将是期望的结果

    【讨论】:

      猜你喜欢
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      相关资源
      最近更新 更多