Database

Top 10 examples of pandas Data frame creation in simple steps

Creating a Pandas DataFrame can be done in various ways, depending on the source and format of the data you’re working with. Below are ten examples that demonstrate different methods to create a Pandas DataFrame in Python. To follow along with these examples, make sure you’ve installed the Pandas library. If you haven’t, you can install it using pip install pandas.

Example 1: Creating an Empty DataFrame

Python
import pandas as pd

# Create an empty DataFrame
df_empty = pd.DataFrame()

Example 2: Creating a DataFrame from Lists

Python
# Create a DataFrame from lists
data = [1, 2, 3, 4, 5]
df_from_list = pd.DataFrame(data, columns=['Numbers'])

Example 3: Creating a DataFrame from a Dictionary

Python
# Create a DataFrame from a dictionary
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df_from_dict = pd.DataFrame(data)

Example 4: Creating a DataFrame from a NumPy Array

Python
import numpy as np

# Create a DataFrame from a NumPy array
array = np.array([[1, 2, 3], [4, 5, 6]])
df_from_array = pd.DataFrame(array, columns=['A', 'B', 'C'])

Example 5: Creating a DataFrame from a CSV File

Python
# Create a DataFrame from a CSV file
#df_from_csv = pd.read_csv('data.csv')

Example 6: Creating a DataFrame from an Excel File

Python
# Create a DataFrame from an Excel file
#df_from_excel = pd.read_excel('data.xlsx')

Example 7: Creating a DataFrame from JSON

Python
# Create a DataFrame from a JSON object
json_data = '{"A": [1, 2, 3], "B": [4, 5, 6]}'
df_from_json = pd.read_json(json_data)

Example 8: Creating a DataFrame with Multi-Index

Python
# Create a multi-index DataFrame
arrays = [
    ['A', 'A', 'B', 'B'],
    [1, 2, 1, 2]
]
index = pd.MultiIndex.from_arrays(arrays, names=('Letters', 'Numbers'))
df_multi_index = pd.DataFrame({'Data': [11, 22, 33, 44]}, index=index)

Example 9: Creating a DataFrame from a SQL Database

Python
import sqlite3

# Create a SQLite database connection
conn = sqlite3.connect("database.db")

# Create a DataFrame from a SQL query
df_from_sql = pd.read_sql_query("SELECT * FROM table_name", conn)

Example 10: Creating a DataFrame from a Series

Python
# Create a DataFrame from a Pandas Series
series = pd.Series([1, 2, 3], name='Numbers')
df_from_series = pd.DataFrame(series)

Note:

For the examples that read from files or databases (Examples 5, 6, 9), the corresponding code is commented out because the files or databases are not actually present in this environment. To run those examples, you would need to uncomment the code and have the appropriate file or database available.