Home  >  Article  >  Backend Development  >  How to Insert a Row at the Beginning of a Pandas Dataframe?

How to Insert a Row at the Beginning of a Pandas Dataframe?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-23 06:37:30713browse

How to Insert a Row at the Beginning of a Pandas Dataframe?

Inserting a Row into a Pandas Dataframe

This guide aims to assist individuals seeking to add or insert a new row to their Pandas dataframe. The problem at hand involves a dataframe containing the following data:

<br>s1 = pd.Series([5, 6, 7])<br>s2 = pd.Series([7, 8, 9])</p>
<p>df = pd.DataFrame([list(s1), list(s2)], columns=["A", "B", "C"])</p>
<p>A  B  C<br>0  5  6  7<br>1  7  8  9</p>
<p>[2 rows x 3 columns]<br>

The task is to insert a new row with the values [2, 3, 4] to produce:

</p>
<pre class="brush:php;toolbar:false">A  B  C

0 2 3 4
1 5 6 7
2 7 8 9

Solution

To accomplish this, we can use the loc() function to assign a row to a specific index:

<br>df.loc[-1] = [2, 3, 4]  # adding a row<br>

However, this adds the new row to the end of the dataframe. To ensure the new row appears at the beginning, we need to shift the existing indices to the next consecutive numbers:

<br>df.index = df.index   1  # shifting index<br>

Finally, to restore the sorted index, we use:

<br>df = df.sort_index()  # sorting by index<br>

With these steps, you can successfully insert a new row at the beginning of your dataframe.

To delve deeper into Pandas indexing and setting with enlargement, refer to the official Pandas documentation.

The above is the detailed content of How to Insert a Row at the Beginning of a Pandas Dataframe?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn