ThatQuantDude
ThatQuantDude

Reputation: 833

Insert row at position [0] of a dataframe

I have a frame like this one, where I insert a new row

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])

which gives me this

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

How can I get my 'NewStock' entry to be inserted at row 0? I want this order

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

Upvotes: 1

Views: 1238

Answers (1)

RichSmith
RichSmith

Reputation: 940

I think you can use pd.concat() if they're both dataframes.

So maybe something like this?

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])

Upvotes: 1

Related Questions