Wednesday, April 24, 2024
HomejQuery3 Examples to Add Column in a Pandas Information Body

3 Examples to Add Column in a Pandas Information Body


The right way to add a column in an current knowledge body utilizing Pandas?

On this tutorial, we’ll present you other ways of including columns within the Pandas knowledge body.

For the examples, now we have the next knowledge body created:

Code:



Output:

Utilizing the insert technique of the info body

The insert is a knowledge body technique that’s used so as to add a column within the specified place.

A replica column identify will also be added if allow_duplicate is about to True.

See the instance beneath the place we’ll add a brand new column (“Distinction”) within the above-created knowledge body.

Code:



Output:



How did it work?

  • We need to add a brand new column with the identify “Distinction” within the DF.
  • Within the insert technique, we specified place 1 (0-based index) for the “Distinction” column.
  • Through the use of insert, you might also present knowledge. We supplied knowledge within the checklist.

Second Approach – need to add a column on the finish of the present Information Body?

That is the simplest approach of including a brand new column together with knowledge within the current knowledge body. Nevertheless, the disadvantage is, it will probably add a column on the finish.

For that, merely use the DF identify together with the brand new column and assign the values in an inventory – that’s it.

Take a look on the instance beneath the place we’ll add the “Distinction” column within the above-created DF.

Code:



Outcome:

You may see the newly added column is positioned on the finish of DF.

Third approach – Utilizing a dictionary/map for including a column

You might also use a Python dictionary and map mixture for including a brand new column within the current knowledge body.

Code:



Output:



How did it work?

  • In that case, we handed the dictionary to the map
  • It’s going to carry out a lookup and return the related worth for that key.
  • Alternatively, we used a column from the present DF and handed a brand new column’s worth to it.

Conclusion:

Resulting from its flexibility (for permitting including columns at any place), we might categorize Information Body’s insert technique as the higher approach for including columns within the knowledge body.


RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments