Adding a new column to an existing DataFrame in Python Pandas



To add a new column to an existing DataFrame we can just make a column and assign values to it that is equal to the same number of rows with other columns.

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.

  • Print the input DataFrame.

  • Create a new column, a, and assign values to this column.

  • Print the DataFrame, df.

Example

 Live Demo

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 1, 9],
      "y": [4, 1, 5, 10],
      "z": [4, 1, 5, 0]
   }
)
print "Input DataFrame is:
", df df['a'] = [2, 4, 1, 0] print "After adding new column:
", df

Output

Input DataFrame is:
   x  y  z
0  5  4  4
1  2  1  1
2  1  5  5
3  9 10  0

After adding new column:
   x  y  z  a
0  5  4  4  2
1  2  1  1  4
2  1  5  5  1
3  9 10  0  0

Advertisements