Add a column to DataFrame Columns
We can add a new column to an existing DataFrame using different ways. For the demonstration, first, we have to write a code to read the existing file, which consists of some columns in a DataFrame.
The above code read the existing csv file and shows the data values column as the output.
Output
Name | Hire Date | Salary | Leaves Remaining |
---|---|---|---|
0 John Idle | 03/15/14 | 50000.0 | 10 |
1 Smith Gilliam | 06/01/15 | 65000.0 | 8 |
2 Parker Chapman | 05/12/14 | 45000.0 | 10 |
3 Jones Palin | 11/01/13 | 70000.0 | 3 |
4 Terry Gilliam | 08/12/14 | 48000.0 | 7 |
5 Michael Palin | 05/23/13 | 66000.0 | 8 |
Add new columns to a DataFrame using [] operator
If we want to add any new column at the end of the table, we have to use the [] operator. Let’s add a new column named “Age” into “aa” csv file.
This code adds a column “Age” at the end of the aa csv file. So, the new table after adding a column will look like this:
Name Hire Date Salary Leaves Remaining Age 0 John Idle 03/15/14 50000.0 10 24 1 Smith Gilliam 06/01/15 65000.0 8 24 2 Parker Chapman 05/12/14 45000.0 10 24 3 Jones Palin 11/01/13 70000.0 3 24 4 Terry Gilliam 08/12/14 48000.0 7 24 5 Michael Palin 05/23/13 66000.0 8 24
In the above code, Age value has defined the universal value that means its value is common to all the rows. If we specify a column name that does not exist, Pandas will throw an error.
For ex:
In the above code, Pandas will throw an error because the Designation column does not exist.
But if we assign a value to that column, Pandas will generate a new column automatically at the end of the table.
Add new columns in a DataFrame using insert()
We can also add a new column at any position in an existing DataFrame using a method name insert.
For the demonstration, first, we have to write a code to read the existing file that consists of some columns in a DataFrame.
The above code read the existing csv file and shown the data values column in the output.
Output
Name Hire Date Salary Leaves Remaining 0 John Idle 03/15/14 50000.0 10 1 Smith Gilliam 06/01/15 65000.0 8 2 Parker Chapman 05/12/14 45000.0 10 3 Jones Palin 11/01/13 70000.0 3 4 Terry Gilliam 08/12/14 48000.0 7 5 Michael Palin 05/23/13 66000.0 8
Let’s add a new column name “Department” into an existing “aa” csv file using insert method.
Output
Name Hire Date Department Salary Leaves Remaining 0 John Idle 03/15/14 B.Sc 50000.0 10 1 Smith Gilliam 06/01/15 B.Sc 65000.0 8 2 Parker Chapman 05/12/14 B.Sc 45000.0 10 3 Jones Palin 11/01/13 B.Sc 70000.0 3 4 Terry Gilliam 08/12/14 B.Sc 48000.0 7 5 Michael Palin 05/23/13 B.Sc 66000.0 8