Pandas version of rbind

前端 未结 4 803
野的像风
野的像风 2021-02-01 12:03

In R, you can combine two dataframes by sticking the columns of one onto the bottom of the columns of the other using rbind. In pandas, how do you accomplish the same thing? It

4条回答
  •  别跟我提以往
    2021-02-01 12:19

    import pandas as pd 
    import numpy as np
    

    If you have a DataFrame like this:

    array = np.random.randint( 0,10, size = (2,4) )
    df = pd.DataFrame(array, columns = ['A','B', 'C', 'D'], \ 
                               index = ['10aa', '20bb'] )  ### some crazy indexes
    df
    
          A  B  C  D
    10aa  4  2  4  6
    20bb  5  1  0  2
    

    And you want add some NEW ROW which is a list (or another iterable object):

    List = [i**3 for i in range(df.shape[1]) ]
    List
    [0, 1, 8, 27]
    

    You should transform list to dictionary with keys equals columns in DataFrame with zip() function:

    Dict = dict(  zip(df.columns, List)  )
    Dict
    {'A': 0, 'B': 1, 'C': 8, 'D': 27}
    

    Than you can use append() method to add new dictionary:

    df = df.append(Dict, ignore_index=True)
    df
        A   B   C   D
    0   7   5   5   4
    1   5   8   4   1
    2   0   1   8   27
    

    N.B. the indexes are droped.

    And yeah, it's not as simple as cbind() in R :(

提交回复
热议问题