简体   繁体   English

将数据框插入数据框-Python / Pandas

[英]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). 问题是很容易说明的,如何在给定的点(索引的10和11之间)将具有几个值的数据帧插入到较大的数据帧中。 Meaning that .append cant be used 意味着不能使用.append

You can use concat with sliced df by loc : 您可以通过locconcat与切片df一起使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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