How To Append Two Columns In Python

In this tutorial, we will learn how to append two columns in Python by using Pandas, a powerful and easy-to-use data manipulation library.

Appending two columns is useful when we want to combine the data from two related columns to perform analysis or manipulation.

We will cover how to combine two columns using Pandas functions like ‘concat’ and ‘assign’ as well as manual concatenation using a for a loop.

Step 1: Installing pandas

Before we start, ensure that you have Pandas installed in your Python environment. If you do not have it installed, you can install it using pip:

Step 2: Importing pandas and loading data

First, we need to import pandas and load our dataset into a DataFrame, which is the main data structure of the Pandas library. In our example, we’ll use a simple CSV file containing information about fruits and their prices:

fruit_data.csv:

fruit,price
apple,0.5
banana,0.3
cherry,1.0

To load the data, we use the following code:

Output:

    fruit  price
0   apple    0.5
1  banana    0.3
2  cherry    1.0

Step 3: Appending two columns using the ‘concat’ function

The first method to append two columns is using the ‘concat’ function provided by Pandas library. Here’s the code to combine the ‘fruit’ and ‘price’ columns:

Output:

    fruit  price fruit_and_price
0   apple    0.5     apple 0.5
1  banana    0.3    banana 0.3
2  cherry    1.0    cherry 1.0

Step 4: Appending two columns using the ‘assign’ function

Another way to append two columns is using the Pandas ‘assign’ function. This function creates a new column in the DataFrame and allows us to merge the values from the two columns. Here’s the code to do this:

Output:

    fruit  price fruit_and_price fruit_and_price2
0   apple    0.5     apple 0.5       apple 0.5
1  banana    0.3    banana 0.3      banana 0.3
2  cherry    1.0    cherry 1.0      cherry 1.0

Step 5: Appending two columns using a for loop

Finally, we can also append two columns by creating a new column and iterating through the DataFrame, combining the values of the two columns using a for loop. Here’s how to do it:

Output:

    fruit  price fruit_and_price fruit_and_price2 fruit_and_price3
0   apple    0.5     apple 0.5       apple 0.5       apple 0.5
1  banana    0.3    banana 0.3      banana 0.3      banana 0.3
2  cherry    1.0    cherry 1.0      cherry 1.0      cherry 1.0

Full Code

Conclusion

In this tutorial, we learned three different methods to append two columns in Python using the Pandas library. Using ‘concat’, ‘assign’, or a for loop, depending on the situation and your comfort level with each approach.

With these techniques in your toolbox, you are now better equipped to manipulate and analyze data stored in DataFrames.