【问题标题】:Merging two dataframes with overlapping and non-overlapping column names合并具有重叠和不重叠列名的两个数据框
【发布时间】:2020-11-17 23:42:14
【问题描述】:

我有两个行长相同但列数不同的数据帧(第一个数据帧有 ~57,而第二个数据帧有 ~28)。

每个数据框中的前几列彼此相同(相同的名称/值),每个数据框中的尾随 "Category" 列之间只有一些重叠(有时名称相同,有时相同的值)。在每个数据帧的 “类别” 列中,值为 1 或 0。

我想将两个数据框合并到第一列(Document #);但是,如果 "Category" 列名在两个数据框之间相同,对于重复列中的每一行单元格,我想将最大数量作为最终值。

我在下面提供了我正在使用的一些简化示例数据的屏幕截图(实际数据有更多“类别” 列)。在数据中,您可以看到df1df2红色 中有两个重叠的Category 列(所有值都是int)。我想将两者合并在一起(同时保持不重叠的列),并将重叠列中的值更新为两列之间的最大值。

我该怎么做?我尝试过使用combine_first 函数,但我也希望能够加入非重叠列。还想尝试以编程方式完成此操作,因为列数太大而无法手动查看和切片,以及列名、位置和编号根据我输入的数据动态变化的事实它。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以通过“文档#”合并两个数据框,然后使用axis=1 跨常见类别执行特定计算。这是一种可扩展的方法:

    # Merge dataframes
    df = df1.merge(df2, on='Document #')
    
    # Get common category names across datasets
    common_cat_cols = df1.columns[df1.columns.str.startswith('Category') & (df1.columns.isin(df2.columns))]
    # Get common category names across datasets with suffixes for posterior removal
    common_cat_cols2remove = [cat + suffix for cat in common_cat_cols for suffix in ['_x','_y']]
    
    # Calculate max value per common category 
    common_cat_max = {col: df[[f'{col}_x', f'{col}_y']].max(axis=1) for col in common_cat_cols}
    
    # Insert the target-columns in the merged dataframe
    df = df.assign(**common_cat_max).drop(columns=common_cat_cols2remove)
    
    # Now, we just re-order the columns to get the expected output
    new_col_order = sum([['Document #'], ['Document Text_' + s for s in ['x','y']] + sorted(df.columns[df.columns.str.startswith('Category')])], [])
    df = df[new_col_order]
    print(df)
    

    输出:

       Document # Document Text_x Document Text_y  Category A  Category B   Category C  Category D  Category E  Category F  Category G  
    0           1               a               a           1           0            1           0           1           0           1  
    1           2              as              as           1           0            1           0           1           0           1  
    2           3             asd             asd           1           1            1           0           1           0           1  
    3           4            asdf            asdf           1           1            1           0           0           1           1  
    4           5           asdfa           asdfa           1           0            1           1           1           1           1  
    5           6          asdfas          asdfas           1           0            1           1           1           0           0  
    6           7         asdfasd         asdfasd           0           1            1           1           1           0           0  
    7           8        asdfasdf        asdfasdf           1           1            1           1           1           0           0 
    

    如您所见,我保持“文档文本”不变,因为我不知道您想对它们做什么。最好的!


    数据:

    df1 = pd.DataFrame({
        'Document #': range(1,9),
        'Document Text': ['a','as','asd','asdf','asdfa','asdfas','asdfasd','asdfasdf'],
        'Category A': [1,0,0,0,0,0,0,1],
        'Category B': [0,0,1,1,0,0,1,1],
        'Category C': [1,0,0,0,0,0,0,0],
        'Category D': [0,0,0,0,1,1,1,1],
        'Category E': [1,1,1,0,1,1,1,1]
    })
    
    df2 = pd.DataFrame({
        'Document #': range(1,9),
        'Document Text': ['a','as','asd','asdf','asdfa','asdfas','asdfasd','asdfasdf'],
        'Category A': [1,1,1,1,1,1,0,0],
        'Category C': [0,1,1,1,1,1,1,1],
        'Category F': [0,0,0,1,1,0,0,0],
        'Category G': [1,1,1,1,1,0,0,0]
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 2023-02-02
      • 2019-03-02
      • 1970-01-01
      • 2016-10-14
      相关资源
      最近更新 更多