How to Add a New Column to a Pandas Dataframe Object in Python



Python


In this article, we show how to add a new column to a pandas dataframe object in Python.

So if you have an existing pandas dataframe object, you are free to do many different modifications, including adding columns or rows to the dataframe object, deleting columns or rows, updating values, etc.

We will show in this article how you can add a column to a pandas dataframe object in Python.

So we below we create a dataframe object that has columns, 'W', 'X', and 'Y'.

We will then add 2 columns to this dataframe object, column 'Z' and column 'M'

Adding a new column to a pandas dataframe object is relatively simply. You just declare the columns and set it equal to the values that you want it to have. And that's all.

Adding a new column to a pandas dataframe object is shown in the following code below.



So let's now go over the code.

So we first have to import the pandas module. We do this with the line, import pandas as pd.

as pd means that we can reference the pandas module with pd instead of writing out the full pandas each time.

We import rand from numpy.random, so that we can populate the DataFrame with random values. In other words, we won't need to manually create the values in the table. The randn function will populate it with random values.

We create a variable, dataframe1, which we set equal to, pd.DataFrame(randn(4,3),['A','B','C','D',],['X','Y','Z'])

This creates a DataFrame object with 4 rows and 3 columns.

The rows are 'A', 'B', 'C', and 'D'.

The columns are 'W', 'X', and 'Y'.

After we output the dataframe1 object, we get the DataFrame object with all the rows and columns, which you can see above.

We then add a new column, 'Z'. This column is equal to the 'X' and 'Y' columns added together.

We then show the dataframe object, which now has 4 columns, 'W', 'X', 'Y', and 'Z'

We then add another column, 'M'. This column is set equal to values, 5,8,18,22.

We then show the complete dataframe object, which now has 5 columns, 'W', 'X', 'Y', 'Z', and 'M'.

We then add another column, 'P', which we set equal to 4 random float numbers.

We then show the complete dataframe object, which now has 6 columns, 'W', 'X', 'Y', 'Z', 'M', and 'P'.

So this is how we can add new columns to a pandas Dataframe object in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...