【问题标题】:Pandas join only a certain column熊猫只加入某个列
【发布时间】:2019-11-21 16:15:53
【问题描述】:

我有数据框 A 和数据框 B,我想将 B 加入 A,但只针对 B 上的某个列。像这样:

dataA = ['a', 'c', 'd', 'e']
A = pd.DataFrame(dataA, columns=['testA'])

dataB = [['a', 1, 'asdf'], 
        ['b', 2, 'asdf'], 
        ['c', 3, 'asdf'], 
        ['d', 4, 'asdf'], 
        ['e', 5, 'asdf']]
B = pd.DataFrame(data1, columns=['testB', 'num', 'asdf'])

Out[1]: A
    testA
0   a
1   c
2   d
3   e

Out[2]: B
    testB   num     asdf
0   a       1       asdf
1   b       2       asdf
2   c       3       asdf
3   d       4       asdf
4   e       5       asdf

我当前的代码是:

Out[3]: A.join(B.set_index('testB'), on='testA')
    testA   num     asdf
0   a       1       asdf
1   c       3       asdf
2   d       4       asdf
3   e       5       asdf

我想要的输出只是加入下面的“num”列并忽略“asdf”列,或者如果有更多列,则忽略所有其他列:

Out[4]: A

    testA   num 
0   a       1   
1   c       3   
2   d       4    
3   e       5    

【问题讨论】:

    标签: python pandas dataframe join


    【解决方案1】:

    一种方法可能是使用merge

    new_df= A.merge(B, how='left', left_on='testA', right_on='testB')[['testA', 'num']]
    

    结果:

      testA  num
    0     a    1
    1     c    3
    2     d    4
    3     e    5
    

    【讨论】:

      【解决方案2】:

      使用map,首先创建一个pd.Series,将您带来的列作为值,并在索引中设置“映射”列。这会忽略并且不对其他不需要的列做任何工作:

      A['num'] = A['testA'].map(B.set_index('testB')['num'])
      A
      

      输出:

        testA  num
      0     a    1
      1     c    3
      2     d    4
      3     e    5
      

      【讨论】:

        【解决方案3】:

        使用你已有的,只保留你想要的列。

        z = a.join(b.set_index('testB'), on='testA')[["testA","num"]]
        

        输出:

            testA   num
        0   a       1
        1   c       3
        2   d       4
        3   e       5
        

        【讨论】:

          猜你喜欢
          • 2014-09-21
          • 2023-01-24
          • 1970-01-01
          • 2015-04-18
          • 2023-03-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多