Skip to main content
 首页 » 编程设计

python之如何根据列值而不是索引来 pd.concat 数据帧

2025年05月04日15mfrbuaa

我有一个表示为 DF_0 的元数据数据帧,然后是一个实际数据 (DF_1) 的数据帧。我想在我的数据帧上使用 pd.concat 但不考虑索引。 DF_0 的索引是任意的,DF_1 的索引对应于 DF_0 的 attr_1 中的值。

我能想到的唯一方法是:

(1) 使 attr_1 成为我的索引然后合并,我不想这样做;或

(2) 排序然后合并 [但丢失的数据可能会搞砸]。感觉pandas已经想到了这一点。

有谁知道使用 pd.concat 或类似方法 [我的真实数据有字符串、 float 、整数] 来合并 2 个 [或更多?] 沿“轴”由特定数据框中特定列的值表示?

值可能按顺序排列,也可能不按顺序排列。我上面描述的方法是唯一的方法吗?它们看起来很乱......

DF_0 = pd.DataFrame(np.arange(15).reshape(5,3),  
                    columns=["attr_%d"%j for j in range(3)]) 
#    attr_0  attr_1  attr_2 
# 0       0       1       2 
# 1       3       4       5 
# 2       6       7       8 
# 3       9      10      11 
# 4      12      13      14 
 
DF_1 = pd.DataFrame([[0,1,0,1,1],[0,0,0,1,0],[1,1,1,0,1]],  
                     index = ["other_%d"%j for j in range(3)],  
                     columns = [1,4,7,10,13]).T 
#     other_0  other_1  other_2 
# 1         0        0        1 
# 4         1        0        1 
# 7         0        0        1 
# 10        1        1        0 
# 13        1        0        1 
 
# What I want 
DF_X = pd.DataFrame( 
                    np.concatenate([DF_0.as_matrix(), DF_1.as_matrix()], axis=1),  
                    columns=list(DF_0.columns) + list(DF_1.columns)) 
#    attr_0  attr_1  attr_2  other_0  other_1  other_2 
# 0       0       1       2        0        0        1 
# 1       3       4       5        1        0        1 
# 2       6       7       8        0        0        1 
# 3       9      10      11        1        1        0 
# 4      12      13      14        1        0        1 

请您参考如下方法:

您想沿着 DF_0 的 attr_1 列和 DF_1 的索引合并:

DF_X = pd.merge(DF_0, DF_1, left_on='attr_1', right_index=True) 
print(DF_X) 

输出:

   attr_0  attr_1  attr_2  other_0  other_1  other_2 
0       0       1       2        0        0        1 
1       3       4       5        1        0        1 
2       6       7       8        0        0        1 
3       9      10      11        1        1        0 
4      12      13      14        1        0        1