Home >Backend Development >Python Tutorial >How to Insert a Row into a Pandas Dataframe using loc, Shifting Index, and Sorting

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

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

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>
   A  B  C
0  5  6  7
1  7  8  9

[2 rows x 3 columns]

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>

2. Shift Index by 1:

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

3. Sort by Index:

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

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

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!

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