How to make a table in Python

Create a table in Python using the Pandas library, with an example using the 'head()' function.

Creating Tables in Python

Tables can be created using the pandas library in Python. This library contains a DataFrame class which allows one to create tables from various data sources such as dictionaries, lists, and series objects. DataFrames can be manipulated and visualized with ease. Below is an example of how to create a simple table with three columns and four rows.


import pandas as pd

# data
data = {'Name':['John', 'Bob', 'James', 'Alice'],
        'Age':[20, 30, 40, 25],
        'Gender':['M', 'M', 'M', 'F']}

# creating dataframe
df = pd.DataFrame(data)

# print dataframe
print(df)

The output of the code above is the following:


   Name  Age Gender
0  John   20      M
1   Bob   30      M
2  James   40      M
3 Alice   25      F

The above example shows how to create a simple table with three columns and four rows. The data dictionary contains the data that is used to populate the table. The pd.DataFrame() function is used to create the table from the data. Finally, the print() function is used to view the table.

In summary, tables can be created in Python using the pandas library. The DataFrame class allows one to create tables from various data sources such as dictionaries, lists, and series objects. The pd.DataFrame() function is used to create the table from the data, and the print() function is used to view the table.

Answers (0)