How To Insert A Column To A DataFrame?


How To Insert A Column To A DataFrame?

Table Of Contents:

  1. Syntax For inserting A Column.
  2. Examples Of Inserting A Column.

(1) Syntax:

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

Description:

  • Insert column into DataFrame at the specified location.

  • Raises a ValueError if the column is already contained in the DataFrame, unless allow_duplicates is set to True.

Parameters:

  • loc: int – Insertion index. Must verify 0 <= loc <= len(columns).
  • column: str, number, or hashable object Label of the inserted column.
  • value: Scalar, Series, or array-like
  • allow_duplicates: bool, optional, default lib.no_default

(2) Examples Of ‘iloc’ Keyword:

Example-1

import pandas as pd
student = {'Name':['Subrat','Abhispa','Arpita','Anuradha','Namita'],
          'Roll_No':[100,101,102,103,104],
          'Subject':['Math','English','Science','History','Commerce'],
          'Mark':[95,88,76,73,93]}
student_object = pd.DataFrame(student)
student_object

Output:

student_object.insert(loc=4,column='Gender',value=['Male','Female','Female','Female','Female'])
student_object

Output:

Note:

  • Here we have inserted the ‘Gender’ column at index position ‘4’.

Leave a Reply

Your email address will not be published. Required fields are marked *