Home>

I want to insert the index x th created df2 of df1

df1

date A B C
2020-11-14 Five 1822 hoge
2020-11-14 6 1899 hoge
2020-11-14 3 1442 hoge
2020-11-14 Four 1255 hoge

df2

df2 = pd.DataFrame (
    [
        ['2020-11-14', 5, '2222','fuga'],
        ['2020-11-14', 6, '881','fuga'],
    ]
)


When using pd.concat, it is vertically connected as it is.

What should I do to make it look like the following?

date A B C
2020-11-14 Five 1822 hoge
2020-11-14 6 1899 hoge
2020-11-14 3 1442 hoge
2020-11-14 Five 2222 fuga
2020-11-14 6 881 fuga
2020-11-14 Four 1255 hoge
  • Answer # 1

    Let's divide df1 vertically in slice notation and concat with df2 in between.
    In addition, in the questioner's code, the columns of df2 are different from df1, so if you concat as it is, it will be misaligned. Therefore, copy columns as preprocessing. In addition, reset_index that reassigns the index is inserted as post-processing.

    import pandas as pd
    import io
    data ='''
    Date A B C
    2020-11-14 5 1822 hoge
    2020-11-14 6 1899 hoge
    2020-11-14 3 1442 hoge
    2020-11-14 4 1255 hoge
    '''
    df1 = pd.read_csv (io.StringIO (data), delimiter ='\ s +')
    df2 = pd.DataFrame (
        [
            ['2020-11-14', 5, '2222','fuga'],
            ['2020-11-14', 6, '881','fuga'],
        ]
    )
    # Here is the answer body
    x = 3
    df2.columns = df1.columns
    df = pd.concat ([df1 [: x], df2, df1 [x:]]). reset_index (drop = True)
    print (df)
    # Date A B C
    # 0 2020-11-14 5 1822 hoge
    # 1 2020-11-14 6 1899 hoge
    # 2 2020-11-14 3 1442 hoge
    # 3 2020-11-14 5 2222 fuga
    # 4 2020-11-14 6 881 fuga
    # 5 2020-11-14 4 1255 hoge