【问题标题】:Merging with pandas while keeping NaNs at bottom与 pandas 合并,同时将 NaN 保持在底部
【发布时间】:2016-04-10 20:13:02
【问题描述】:

假设我有 3 个数据框,每个数据框都有一列。在每个 df 中,行数略多于前一个。例如: 我想得到这个:

df1 =       col1 
        1   a
        2   b
        3   c

df2 =       col2 
        1   x
        2   y
        3   z
        4   w
        5   q

df3 =       col3 
        1   A
        2   B
        3   C
        4   D
        5   E
        6   F
        7   G

我想得到这个:

res =       col1    col2    col3
        1   a       x       A
        2   b       y       B
        3   c       z       C
        4   -       w       D
        5   -       q       E
        6   -       -       F
        7   -       -       G

也就是说,我希望行保持添加顺序,因此 NaN (-) 保留在底部。 我试过这个:

import pandas as pd
total = pd.DataFrame()

total = pd.merge(total,df1,how='outer',left_index=True,right_index=True)
total = pd.merge(total,df2,how='outer',left_index=True,right_index=True)
total = pd.merge(total,df3,how='outer',left_index=True,right_index=True)

但我一直以看似随机的顺序获取表格。像这样的东西:

res =       col1    col2    col3
        1   a       x       A
        4   -       w       D
        3   c       z       C
        5   -       q       E
        2   b       y       B
        7   -       -       G
        6   -       -       F

如何强制最终的 df 采用所需的形式? 谢谢!

【问题讨论】:

    标签: python python-2.7 pandas merge dataframe


    【解决方案1】:

    concat 并传递 axis=1 以按列进行:

    In [203]:
    pd.concat([df1,df2,df3], axis=1)
    
    Out[203]:
      col1 col2 col3
    1    a    x    A
    2    b    y    B
    3    c    z    C
    4  NaN    w    D
    5  NaN    q    E
    6  NaN  NaN    F
    7  NaN  NaN    G
    

    【讨论】:

      猜你喜欢
      • 2019-07-26
      • 2022-08-16
      • 1970-01-01
      • 1970-01-01
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      相关资源
      最近更新 更多