Insert a row to pandas dataframe Insert a row to pandas dataframe python python

Insert a row to pandas 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.


Not sure how you were calling concat() but it should work as long as both objects are of the same type. Maybe the issue is that you need to cast your second vector to a dataframe? Using the df that you defined the following works for me:

df2 = pd.DataFrame([[2,3,4]], columns=['A','B','C'])pd.concat([df2, df])


One way to achieve this is

>>> pd.DataFrame(np.array([[2, 3, 4]]), columns=['A', 'B', 'C']).append(df, ignore_index=True)Out[330]:    A  B  C0  2  3  41  5  6  72  7  8  9

Generally, it's easiest to append dataframes, not series. In your case, since you want the new row to be "on top" (with starting id), and there is no function pd.prepend(), I first create the new dataframe and then append your old one.

ignore_index will ignore the old ongoing index in your dataframe and ensure that the first row actually starts with index 1 instead of restarting with index 0.

Typical Disclaimer: Cetero censeo ... appending rows is a quite inefficient operation. If you care about performance and can somehow ensure to first create a dataframe with the correct (longer) index and then just inserting the additional row into the dataframe, you should definitely do that. See:

>>> index = np.array([0, 1, 2])>>> df2 = pd.DataFrame(columns=['A', 'B', 'C'], index=index)>>> df2.loc[0:1] = [list(s1), list(s2)]>>> df2Out[336]:      A    B    C0    5    6    71    7    8    92  NaN  NaN  NaN>>> df2 = pd.DataFrame(columns=['A', 'B', 'C'], index=index)>>> df2.loc[1:] = [list(s1), list(s2)]

So far, we have what you had as df:

>>> df2Out[339]:      A    B    C0  NaN  NaN  NaN1    5    6    72    7    8    9

But now you can easily insert the row as follows. Since the space was preallocated, this is more efficient.

>>> df2.loc[0] = np.array([2, 3, 4])>>> df2Out[341]:    A  B  C0  2  3  41  5  6  72  7  8  9