简体   繁体   中英

insert dataframe into a dataframe - Python/Pandas

Question is pretty self explanatory, how would you insert a dataframe with a couple of values in to a bigger dataframe at a given point (between index's 10 and 11). Meaning that .append cant be used

You can use concat with sliced df by loc :

np.random.seed(100)
df1 = pd.DataFrame(np.random.randint(100, size=(5,6)), columns=list('ABCDEF'))
print (df1)
    A   B   C   D   E   F
0   8  24  67  87  79  48
1  10  94  52  98  53  66
2  98  14  34  24  15  60
3  58  16   9  93  86   2
4  27   4  31   1  13  83

df2 = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df2)
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

#inserted between 4 and 5 index values
print (pd.concat([df1.loc[:4], df2, df1.loc[4:]], ignore_index=True))
    A   B   C   D   E   F
0   8  24  67  87  79  48
1  10  94  52  98  53  66
2  98  14  34  24  15  60
3  58  16   9  93  86   2
4  27   4  31   1  13  83
5   1   4   7   1   5   7
6   2   5   8   3   3   4
7   3   6   9   5   6   3
8  27   4  31   1  13  83

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM