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

Mary-Kate Olsen
Release: 2024-10-23 06:37:30
Original
706 people have browsed it

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>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">A  B  C
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!