Skip to main content
 首页 » 编程设计

python之在 Pandas 中跨多列排列行值

2025年05月04日19tintown

我有 3 个 pandas 数据框,每个包含 1 列。

df1 = pd.DataFrame({'col1':[111, 222, 333, 444, 555]}) 
df2 = pd.DataFrame({'col2':[222, 333, 555]}) 
df3 = pd.DataFrame({'col3':[111, 222, 333, 666]}) 

我知道如何沿着列连接它们:

pd.concat([df1, df2, df3], axis=1) 
 
col1   col2   col3 
111    222    111 
222    333    222 
333    555    333 
444    NaN    666 
555    NaN    NaN 

我想要的是,所有列的第一行必须是111,如果111不可用,它将是NaN ,这适用于后续行。

我想对数字进行排序,以便最终输出如下:

col1   col2   col3 
111    NaN    111 
222    222    222 
333    333    333 
444    NaN    NaN 
555    555    NaN 
NaN    NaN    666 

这在 Pandas 中可能吗?

请您参考如下方法:

是的,有可能,使用set_index带有参数 drop=False 用于列中的索引:

df1 = pd.DataFrame({'col1':[111, 222, 333, 444, 555]}) 
df2 = pd.DataFrame({'col2':[222, 333, 555]}) 
df3 = pd.DataFrame({'col3':[111, 222, 333, 666]}) 
 
df11 = df1.set_index('col1', drop=False) 
df22 = df2.set_index('col2', drop=False) 
df33 = df3.set_index('col3', drop=False) 
 
dfs1 = [df11, df22, df33] 
df = pd.concat(dfs1, axis=1) 
print (df) 
 
      col1   col2   col3 
111  111.0    NaN  111.0 
222  222.0  222.0  222.0 
333  333.0  333.0  333.0 
444  444.0    NaN    NaN 
555  555.0  555.0    NaN 
666    NaN    NaN  666.0 

df = pd.concat(dfs1, axis=1).reset_index(drop=True) 
print (df) 
 
    col1   col2   col3 
0  111.0    NaN  111.0 
1  222.0  222.0  222.0 
2  333.0  333.0  333.0 
3  444.0    NaN    NaN 
4  555.0  555.0    NaN 
5    NaN    NaN  666.0 

如果想按第一列连接:

L = [x.set_index(x.columns[0], drop=False) for x in dfs] 
df = pd.concat(L, axis=1).reset_index(drop=True) 
print (df) 
 
    col1   col2   col3 
0  111.0    NaN  111.0 
1  222.0  222.0  222.0 
2  333.0  333.0  333.0 
3  444.0    NaN    NaN 
4  555.0  555.0    NaN 
5    NaN    NaN  666.0