【问题标题】:Comparing the columns of two data frames?比较两个数据框的列?
【发布时间】:2021-01-17 00:45:25
【问题描述】:

我有两个数据框如下:

  df1:
            id,   f1,   f2,..., f800
            0,     5,  5.6,..,  3,7
            1,   2.4,  1.6,..,  1,7
            2,     3,  2.3,..,  4,4
            ....
            n,   4.7,  9,3,..., 8,2

 df2:
            id,   v1,   v2,..., v200
            0,     5,  5.6,..,  5,7
            1,   2.4,  1.6,..,  6,7
            2,     3,  2.3,..,  4,2
            ....
            n,   4.7,  9,3,..., 3,1

df1 包含 800 个特征,而 df2 仅包含 200 个特征。第二个数据帧 (df2) 是第一个数据帧 (df1) 的一部分。现在,我想找到包含 df2 列/变量的列(在 df1 中)的位置。这里列的值应该是相似的,而不是列的名称。考虑到上面的例子,我想要的输出应该是“f1 和 f2”或者来自 df1 的列 [0, 1]。
有什么办法解决这个问题吗?

【问题讨论】:

  • 如果我理解正确,列的名称不同但值相同?列是连续的还是随机的?如果连续,您只需从 df1 df1[:,:200]中选择前 200 列
  • 列的名称不同(如您在上面的示例中所见),但某些列中的值相似。所以我正在寻找具有相似值的列的索引。
  • 你的意思是索引列的标题吗?
  • 我在我的问题中添加了更多细节。是的,来自 df1 的列标题(df1 中的 f1 和 f2 类似于 df2 中的 v1 和 v2)或来自 df1 的列号。

标签: python arrays dataframe indexing comparison


【解决方案1】:

你需要把这个问题分解成部分 一是寻找共同特征

df1 = pd.DataFrame([[0,1,2,11],[3,4,5,12],[6,7,8,13]], columns=['A','B','C','D'])
df2 = pd.DataFrame([[1,2,11],[4,5,12],[7,8,14]], columns=['a','b','D']) 
common = set(df1.columns) & set(df2.columns)

另一个正在检查这两列是否相似

if(df1[common].equals(df2[common])): 
     print(df1[common])
else:
     print("Nothing common")

为了检查多个列,您可以在 if 条件的顶部创建一个循环。

【讨论】:

    【解决方案2】:

    我会连接这两个数据帧,所以我确信只有相同的索引存在

    result = pd.concat([df1, df2], axis=1, join='inner')
    

    那么你可以使用这个代码:

    import pandas as pd 
      
    def getDuplicateColumns(df): 
        duplicateColumnNames = set() 
        
        for x in range(df.shape[1]-200): 
            col = df.iloc[:, x] 
              
            for y in range(df.shape[1]-200, df.shape[1]):  
                otherCol = df.iloc[:, y] 
                #if the columns are equal mark it down  
                if col.equals(otherCol): 
                    duplicateColumnNames.add(df.columns.values[y]) 
                    #here you can mark down both names, so you map them
        return list(duplicateColumnNames) 
    
    cols = getDuplicateColumns(result)
    

    然后您可以对返回的选定列执行任何您需要的操作,即删除多余的列。 200 是您的第二个 df 中的预期 cols 数,您可以将其作为参数发送。如果您确定 df1 中的每个 col 在 df2 中只有 1 个匹配项,您也可以在找到匹配项后打破内部循环。

    【讨论】:

      【解决方案3】:

      常用列:

      common = set(df1.columns) & set(df2.columns)
      

      要获取 df2 中存在的 df1 列:

      df1[common]
      

      【讨论】:

      • df1 = pandas.DataFrame([[0,1,2],[3,4,5],[6,7,8]], columns=['A','B','C']); df2 = pandas.DataFrame([[1,2],[4,5],[7,8]], columns=['a','b']); common = set(df1.columns) & set(df2.columns); print(df1[common]) 输出Empty DataFrame...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多