【问题标题】:Concatenate two dataframes based on no of rows根据行数连接两个数据帧
【发布时间】:2018-07-15 18:19:15
【问题描述】:

我有两个数据框:

a b c     d e f
2 4 6     6 7 1
4 7 9     9 5 8
          7 9 6
          5 8 2

现在我想创建一个这样的新数据框:

a b c d e f 
2 4 6 6 7 1 
4 7 9 9 5 8 

也就是说,我只想要第二个数据帧的行,直到行数与第一个数据帧匹配。

【问题讨论】:

  • df1.join(df2)
  • @user3483203 更好!

标签: python pandas


【解决方案1】:

concatjoin = 'inner'

pd.concat([x,y],join = 'inner', axis=1)
Out[184]: 
   a  b  c  d  e  f
0  2  4  6  6  7  1
1  4  7  9  9  5  8

【讨论】:

    【解决方案2】:
    import pandas as pd
    df1=pd.DataFrame({'a': [2, 4], 'b': [4, 7], 'c': [6, 9]})
    df2=pd.DataFrame({'d': [6, 9, 7, 5], 'e': [ 7, 5, 9, 8], 'f': [1,8,6, 2]})
    result = pd.concat([df1,df2],axis=1, join_axes=[df1.index])
    print(result)
    

    参考熊猫文档。真的很好。添加了下面的链接。

    https://pandas.pydata.org/pandas-docs/stable/merging.html

    【讨论】:

      【解决方案3】:
      >>> import pandas as pd
      >>> x = pd.DataFrame({'a': [2, 4], 'b': [4, 7], 'c': [6, 9]})
      >>> y = pd.DataFrame({'d': [6, 9, 7, 5], 'e': [ 7, 5, 9, 8], 'f': [1,8,6, 2]})
      >>> x
         a  b  c
      0  2  4  6
      1  4  7  9
      >>> y
         d  e  f
      0  6  7  1
      1  9  5  8
      2  7  9  6
      3  5  8  2
      
      >>> pd.concat([ x, y], axis=1).dropna()
           a    b    c  d  e  f
      0  2.0  4.0  6.0  6  7  1
      1  4.0  7.0  9.0  9  5  8
      

      【讨论】:

      • pd.concat([df1, df2], axis=1).dropna().astype(int) 将解决某些值被转换为浮点数的问题
      【解决方案4】:

      使用 pandas.concatslicing 我们可以继续:

      a = pd.DataFrame(np.random.randint(10, size=(2,3)), columns=["a", "b", "c"])
      b = pd.DataFrame(np.random.randint(10, size=(4,3)), columns=["d", "e", "f"])
      

      所以这两个 DataFrame 看起来像:

      然后运行:

      result = pd.concat([a, b[:len(a)]], axis=1)
      

      所以结果是:

      【讨论】:

      • 当有人对某个答案投了反对票时,最好解释一下哪里出了问题,这样可以增强答案。
      • @AntonvBR 图像不是代码,它们是数据帧。文本输出在移动设备上更难阅读。
      【解决方案5】:

      您可以使用 join 来加入数据框

      df1 = pd.DataFrame({'a': [2, 4], 'b': [4, 7], 'c': [6, 9]})
      df2= pd.DataFrame({'d': [6, 9, 7, 5], 'e': [ 7, 5, 9, 8], 'f': [1,8,6, 2]})
      df1.join(df2)
      
         a  b  c  d  e  f
      0  2  4  6  6  7  1
      1  4  7  9  9  5  8
      

      【讨论】:

        猜你喜欢
        • 2017-11-02
        • 2016-09-16
        • 2020-09-02
        • 1970-01-01
        • 2022-08-14
        • 2019-12-06
        • 2018-03-30
        • 2020-05-23
        • 2023-04-02
        相关资源
        最近更新 更多