I have a dataframe:
s1 = pd.Series([5, 6, 7])
s2 = pd.Series([7, 8, 9])
df = pd.DataFrame([list(s1), list(s2)], columns = ["A", "B", "C"])
A B C
0 5 6 7
1 7 8 9
[2 rows x 3 columns]
and I need to add a first row [2, 3, 4] to get:
A B C
0 2 3 4
1 5 6 7
2 7 8 9
I've tried append()
and concat()
functions but can't find the right way how to do that.
How to add/insert series to dataframe?
Just assign row to a particular index, using loc
:
df.loc[-1] = [2, 3, 4] # adding a row
df.index = df.index + 1 # shifting index
df = df.sort_index() # sorting by index
And you get, as desired:
A B C
0 2 3 4
1 5 6 7
2 7 8 9
See in Pandas documentation Indexing: Setting with enlargement.