How to Insert a Row into a Pandas DataFrame at a Specified Position?

DDD
Release: 2024-10-23 06:39:01
Original
580 people have browsed it

How to Insert a Row into a Pandas DataFrame at a Specified Position?

Inserting a Row into a Pandas DataFrame

In Pandas, you have a DataFrame and want to insert a row at a specific index or position. A common way is using loc (for label-based indexing) or iloc (for integer-based indexing).

Let's understand this with an example:

Consider the following DataFrame df:

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)
Copy after login

Output:

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

Now, you want to insert a new row (e.g., [2, 3, 4]) to the beginning (index 0) of the existing DataFrame.

To insert a row at a specific index, you can assign the row to the desired index using loc. For instance, to insert [2, 3, 4] as the first row:

df.loc[-1] = [2, 3, 4]
Copy after login

However, this action adds a row before the existing DataFrame, resulting in a negative index. To shift the existing indices up and make the newly inserted row the first row, you can update the indices by incrementing them:

df.index = df.index + 1
Copy after login

Finally, sort the DataFrame by the index to obtain the desired ordering:

df = df.sort_index()
Copy after login

As a result, you get the updated DataFrame with the inserted row at index 0:

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

This approach allows you to insert a new row at any position within a DataFrame by assigning values to a specific index.

The above is the detailed content of How to Insert a Row into a Pandas DataFrame at a Specified Position?. 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
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!