Thursday, April 25, 2024
HomejQueryPandas Information Body Insert technique: Defined with 3 Examples

Pandas Information Body Insert technique: Defined with 3 Examples


Pandas Information Body Insert technique

The information body insert technique is used so as to add a brand new column on the specified place in an information body.

If a newly added column identify already exists then an error happens.

As a way to add a reproduction column, it’s possible you’ll use the allow_duplicate= True

Syntax of insert technique

DataFrame.insert(loc, column, worth, allow_duplicates=_NoDefault.no_default)

An instance of the insert so as to add a brand new column

For our examples, we’ve the next information body created by utilizing this Python program:

Code:



Information Body:



Within the instance under, we’ll solely use three arguments within the insert technique.

The primary argument specifies the place – the place so as to add the column.

It’s a 0-based index, so we offered 2 so as to add the column after the ID column.

Then we offered the column identify and the final argument incorporates the values for the brand new column.

Python program:



Output:

You possibly can see, the Distinction column is added after the primary column “12 months”.

The instance of including a reproduction column

As talked about earlier, Python will generate an error in case you strive including a column identify that already exists. See under the place we used the insert technique for including a column “Identify” within the above-created information body.

Code:



Output:



So, it generated the ValueError.

Utilizing allow_duplicates within the insert technique

As a way to permit including a reproduction column, it’s possible you’ll use the allow_duplicates argument as follows:

allow_duplicates = True

See the identical instance as above and the output.

Code:



Output:

Pandas-df-insert-allow

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments