In this tutorial, we will learn how to print two columns in Python. This can be useful for various applications, such as displaying data in tables or organizing output for better readability.
We will demonstrate how to achieve this using two methods: (1) using the format() function and (2) employing the pandas library.
Method 1: Using the format() function
Step 1: Create two lists to represent the two columns.
1 2 |
column1 = ['A', 'B', 'C', 'D', 'E'] column2 = [1, 2, 3, 4, 5] |
Step 2: Use a for loop and the format() function to print the two columns.
1 2 |
for c1, c2 in zip(column1, column2): print("{:<10} {:<10}".format(c1, c2)) |
This will print the two columns, each having a width of 10 characters:
A 1 B 2 C 3 D 4 E 5
Method 2: Using the Pandas library
The pandas library provides an easy way to manipulate tabular data in Python. In this example, we will create a DataFrame and print it.
Step 1: Install the pandas library if you haven’t already.
1 |
!pip install pandas |
Step 2: Import pandas and create a DataFrame.
1 2 3 4 5 |
import pandas as pd data = {'Column1': ['A', 'B', 'C', 'D', 'E'], 'Column2': [1, 2, 3, 4, 5]} df = pd.DataFrame(data) |
Step 3: Display the DataFrame.
1 |
print(df) |
This will print the DataFrame with the two columns:
Column1 Column2 0 A 1 1 B 2 2 C 3 3 D 4 4 E 5
The Full Code
Method 1: Using the format() function
1 2 3 4 5 |
column1 = ['A', 'B', 'C', 'D', 'E'] column2 = [1, 2, 3, 4, 5] for c1, c2 in zip(column1, column2): print("{:<10} {:<10}".format(c1,c2)) |
Method 2: Using the pandas library
1 2 3 4 5 6 |
import pandas as pd data = {'Column1': ['A', 'B', 'C', 'D', 'E'], 'Column2': [1, 2, 3, 4, 5]} df = pd.DataFrame(data) print(df) |
Conclusion
In this tutorial, we learned two ways to print two columns in Python using the format() function and the pandas library.
Depending on your use case and familiarity with the different methods, you can choose the one that suits your needs best. Utilizing these techniques to organize and display data can significantly improve the readability and presentation of your output.