Creating Series & DataFrames from Scratch
Reading Time: 8 Mins | Level: Beginner to Advanced
1. Creating a Pandas Series
A pd.Series can be created from Python lists, dictionaries, tuples, or NumPy arrays.
A. From a Python List
1import pandas as pd
2
3# Creating a series with custom string index
4temperatures = pd.Series([32.5, 34.0, 31.8, 35.2], index=['Delhi', 'Agra', 'Noida', 'Mathura'], name='Temp_Celsius')
5print(temperatures)
Output:
1Delhi 32.5
2Agra 34.0
3Noida 31.8
4Mathura 35.2
5Name: Temp_Celsius, dtype: float64
B. From a Python Dictionary
When creating a Series from a dictionary, the dictionary keys automatically become the Series Index, and the dictionary values become the data:
1student_scores = {'Amit': 88, 'Sunita': 94, 'Kavita': 91, 'Rahul': 76}
2scores_series = pd.Series(student_scores, name='Math_Score')
3print(scores_series)
Method 1: Dictionary of Lists / Arrays (Most Common)
Here, each key becomes a Column Name, and the corresponding list becomes the column values (all lists must be of equal length):
1data = {
2 'Student_ID': [101, 102, 103, 104],
3 'Name': ['Deepak', 'Ananya', 'Vikas', 'Pooja'],
4 'City': ['Shikohabad', 'Firozabad', 'Agra', 'Lucknow'],
5 'Marks': [85.5, 92.0, 78.5, 95.0]
6}
7
8df = pd.DataFrame(data)
9print(df)
Output:
1 Student_ID Name City Marks
20 101 Deepak Shikohabad 85.5
31 102 Ananya Firozabad 92.0
42 103 Vikas Agra 78.5
53 104 Pooja Lucknow 95.0
Often data comes from REST APIs or MongoDB as a list of JSON records:
1records = [
2 {'Product': 'Laptop', 'Price': 55000, 'Stock': 12},
3 {'Product': 'Mouse', 'Price': 650, 'Stock': 80},
4 {'Product': 'Keyboard', 'Price': 1500, 'Stock': 45}
5]
6
7df_products = pd.DataFrame(records)
8print(df_products)
Method 3: From a 2D NumPy Array with Custom Columns
1import numpy as np
2
3matrix = np.random.randint(10, 100, size=(3, 3))
4df_matrix = pd.DataFrame(matrix, columns=['A', 'B', 'C'], index=['Row_1', 'Row_2', 'Row_3'])
5print(df_matrix)
Once a DataFrame is instantiated, inspect its dimensions and metadata immediately:
1print(df.shape) # (rows, columns) -> (4, 4)
2print(df.columns) # Index(['Student_ID', 'Name', 'City', 'Marks'], dtype='object')
3print(df.index) # RangeIndex(start=0, stop=4, step=1)
4print(df.dtypes) # Datatypes for each column
Interactive Quiz• Knowledge Check
Multiple Choice Questions
When creating a Pandas Series from a standard Python dictionary, what do the dictionary keys become?
If you construct a DataFrame from a dictionary of lists, what requirement must be satisfied?
Which attribute returns a tuple representing the dimensionality (rows, columns) of a DataFrame?
What is the output of df.dtypes?
What does the df.head(3) method do?