【问题标题】:Concatenate only new values of first column of one dataframe to an other one仅将一个数据帧的第一列的新值连接到另一个数据帧
【发布时间】:2021-01-21 10:20:48
【问题描述】:

我找不到只连接 colA 的新值的正确方法。这很简单,我需要将 A 列的新元素从 DF2 添加到 DF1

DF1
colA  colB  colC
 a      5     7
 b      4     5
 c      5     6

DF2
colA  colE  colF
 a      7     e
 b      d     4
 c      f     g
 d      h     h
 e      4     r

我试过这样的简单代码,但输出数据帧不正确:

DF3 = pd.concat([DF1, DF2['ColA']], keys=["ColA"])
DF3.drop_duplicates(subset=['ColA'], inplace=True, keep='last')

结果是 [a, 5, 7] 被删除并替换为 [a, nan, nan]

我需要的是这个:

DF3 merged colA
colA  colB  colC
 a      5     7
 b      4     5
 c      5     6
 d
 e

然后我手动填充 DF3 缺失值。在 DF3 中,我既不需要 colE,也不需要 colF。

【问题讨论】:

    标签: python pandas concatenation


    【解决方案1】:

    你可以使用pandas.DataFrame.merge:

    >>> DF1.merge(DF2, how='outer', on='colA').reindex(DF1.columns, axis=1)
      colA  colB  colC
    0    a   5.0   7.0
    1    b   4.0   5.0
    2    c   5.0   6.0
    3    d   NaN   NaN
    4    e   NaN   NaN
    

    编辑 要删除 NaN 并将其他 val 转换回 int,您可以尝试:

    >>> df.merge(df2['colA'], how='outer').fillna(-1, downcast='infer').replace({-1:''})
      colA colB colC
    0    a    5    7
    1    b    4    5
    2    c    5    6
    3    d          
    4    e          
    
    # if -1 part is a concern, then, convert to "Int64"
    >>> df.astype({'colB': 'Int64', 'colC': 'Int64'}).merge(df2['colA'], how='outer')
      colA  colB  colC
    0    a     5     7
    1    b     4     5
    2    c     5     6
    3    d  <NA>  <NA>
    4    e  <NA>  <NA>
    
    # You can replace the NaN's with string as well:
    >>> df.astype({
          'colB': 'Int64', 
          'colC': 'Int64'
        }).merge(df2['colA'], how='outer').replace({np.nan: ''})
    
      colA colB colC
    0    a    5    7
    1    b    4    5
    2    c    5    6
    3    d          
    4    e          
    

    【讨论】:

    • 谢谢,但它改变了我在最后一列中的所有值...在 colC 中是 1 和 2,现在是 1.0 和 2.0,我无法转换回 int :/
    【解决方案2】:

    删除keep='last' 为默认值keep='first'

    DF3.drop_duplicates(subset=['ColA'], inplace=True, keep='last')
    

    到:

    DF3.drop_duplicates(subset=['ColA'], inplace=True)
    

    【讨论】:

      【解决方案3】:

      或者只是外部合并 DF2[['colA']]

      DF1.merge(DF2[['colA']], how='outer')
      

      【讨论】:

        猜你喜欢
        • 2022-10-12
        • 1970-01-01
        • 2018-02-23
        • 1970-01-01
        • 2023-03-15
        • 1970-01-01
        • 2021-04-26
        • 2021-02-25
        • 1970-01-01
        相关资源
        最近更新 更多