How to Insert a Row into a Pandas Dataframe using loc, Shifting Index, and Sorting

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

How to Insert a Row into a Pandas Dataframe using loc, Shifting Index, and Sorting

Inserting a Row into a Pandas Dataframe

When working with Pandas dataframes, you may encounter the need to insert a new row at a specific location. Suppose you have a dataframe with two series, s1 and s2, represented as follows:

<code class="python">s1 = pd.Series([5, 6, 7])
s2 = pd.Series([7, 8, 9])

df = pd.DataFrame([list(s1), list(s2)],  columns =  ["A", "B", "C"])

print(df)</code>
Copy after login
   A  B  C
0  5  6  7
1  7  8  9

[2 rows x 3 columns]
Copy after login

To add a new row with values [2, 3, 4] as the first row, follow these steps:

1. Assign Row to a Specific Index using loc:

<code class="python">df.loc[-1] = [2, 3, 4]  # adding a row</code>
Copy after login

2. Shift Index by 1:

<code class="python">df.index = df.index + 1  # shifting index</code>
Copy after login

3. Sort by Index:

<code class="python">df = df.sort_index()  # sorting by index</code>
Copy after login

After performing these steps, you will obtain the desired output:

    A  B  C
 0  2  3  4
 1  5  6  7
 2  7  8  9
Copy after login

As explained in the Pandas documentation on Indexing: Setting with enlargement, this approach allows you to add new rows to a dataframe by enlarging the index. The loc function lets you assign values to a specific index, in this case, -1 for the new row. Shifting the index and sorting by index ensures that the new row is inserted as the first row in the dataframe.

The above is the detailed content of How to Insert a Row into a Pandas Dataframe using loc, Shifting Index, and Sorting. 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 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!