在数据帧的位置[0]处插入行

时间:2017-01-24 12:46:20

标签: python dataframe insert

我有一个像这样的框架,我插入一个新行

import pandas as pd

s1 = pd.Series([5, 6, 7])
s2 = pd.Series([11, 12, 13])
s3 = pd.Series([22, 23, 24])

index_lst = ['StockA','StockB','StockC']

df = pd.DataFrame([list(s1), list(s2), list(s3)],  columns =  ["A", "B", "C"], index = index_lst)
insert_line = pd.DataFrame({'A' : 99, 'C' : 98}, index = ['NewStock'])
df2 = pd.concat([df.ix[0:], insert_line])

给了我这个

           A     B   C     
StockA     5  6.00   7  
StockB    11 12.00  13 
StockC    22 23.00  24 
NewStock  11   nan  22  

如何在第0行插入“NewStock”条目?我想要这个订单

           A     B   C     
NewStock  11   nan  22   
StockA     5  6.00   7  
StockB    11 12.00  13 
StockC    22 23.00  24 

1 个答案:

答案 0 :(得分:1)

我认为如果它们都是数据帧,您可以使用pd.concat()

那么也许是这样的?

import pandas as pd

s1 = pd.Series([5, 6, 7])
s2 = pd.Series([11, 12, 13])
s3 = pd.Series([22, 23, 24])

index_lst = ['StockA','StockB','StockC']

df = pd.DataFrame([list(s1), list(s2), list(s3)],  columns =  ["A", "B", "C"], index = index_lst)
insert_line = pd.DataFrame({'A' : 99, 'C' : 98}, index = ['NewStock'])


df = pd.concat([insert_line, df])