Python libraries contain collections of built-in modules that allow developers to perform complex tasks without writing detailed programs from scratch. Each library contains numerous modules that can be imported and utilized.
Technical Profile: Core Python Data Science Libraries
Pandas can be installed via the command line using the Python package installer:
pip install pandas
Note: Both NumPy and Pandas require Python to be pre-installed on the system.
A data structure is a collection of data values and operations that can be applied to that data, enabling efficient storage, retrieval, and modification. Pandas primarily uses two data structures:
A Series is a one-dimensional array containing a sequence of values of any data type (int, float, list, string, etc.), which by default have numeric data labels starting from zero. The data label associated with a particular value is called its index .
To create or use a Series, the Pandas library must first be imported:
import pandas as pd
(A) Creation of Series from Scalar Values:
>>> series1 = pd.Series([10, 20, 30])
>>> print(series1)
0 10
1 20
2 30
dtype: int64
(B) Creation of Series with User-Defined Indices:
>>> series2 = pd.Series(["Kavi", "Shyam", "Ravi"], index=[3, 5, 1])
>>> print(series2)
3 Kavi
5 Shyam
1 Ravi
dtype: object
(C) Creation of Series from NumPy Arrays:
>>> import numpy as np
>>> array1 = np.array([1, 2, 3, 4])
>>> series3 = pd.Series(array1)
>>> print(series3)
0 1
1 2
2 3
3 4
dtype: int32
Note: If index labels are passed with a NumPy array, the length of the index and the array must match, otherwise a ValueError is raised.
(D) Creation of Series from a Dictionary:
>>> dict1 = {'India': 'NewDelhi', 'UK': 'London', 'Japan': 'Tokyo'}
>>> series8 = pd.Series(dict1)
>>> print(series8)
India NewDelhi
UK London
Japan Tokyo
dtype: object
Elements of a Series can be accessed using two primary methods: Indexing and Slicing .
(A) Indexing:
>>> seriesNum = pd.Series([10, 20, 30])
>>> seriesNum[2]
30
Accessing multiple elements using a list of indices:
>>> seriesCapCntry[['UK', 'USA']]
UK London
USA WashingtonDC
dtype: object
(B) Slicing:
Slicing extracts a subset of a Series using the syntax [start:end] .
>>> seriesCapCntry[1:3]
USA WashingtonDC
UK London
dtype: object
>>> seriesCapCntry['USA':'France']
USA WashingtonDC
UK London
France Paris
dtype: object
Reversing a Series using slicing:
>>> seriesCapCntry[::-1]
The following table details the core attributes of a Pandas Series:
| Attribute Name | Purpose | Example Syntax |
|---|---|---|
| name | Assigns or retrieves a name for the Series | series.name = 'Capitals' |
| index.name | Assigns or retrieves a name for the index of the Series | series.index.name = 'Countries' |
| values | Returns a list of values in the Series as a NumPy ndarray | series.values |
| size | Returns the number of elements in the Series | series.size |
| empty | Returns True if the Series is empty, otherwise False | series.empty |
| Method | Explanation | Example Syntax |
|---|---|---|
| head(n) | Returns the first n elements of the Series (default is 5) | series.head(2) |
| count() | Returns the number of non-NaN (non-null) values in the Series | series.count() |
| tail(n) | Returns the last n elements of the Series (default is 5) | series.tail(2) |
Mathematical operations on Series align data based on index labels. If an index is present in one Series but not the other, the resulting value is marked as NaN (Not a Number).
Using Operators vs Methods:
>>> # Addition with operator
>>> seriesA + seriesB
a -9.0
b NaN
c -47.0
>>> # Addition with method and fill_value
>>> seriesA.add(seriesB, fill_value=0)
a -9.0
b 2.0
c -47.0
A DataFrame is a two-dimensional, tabular, labelled data structure containing rows and columns. It has both a row index and a column index, and can store heterogeneous data types.
DataFrames can be created from various inputs:
>>> dFrame = pd.DataFrame([array1, array2], columns=['A', 'B', 'C', 'D'])
>>> listDict = [{'a': 10, 'b': 20}, {'a': 5, 'b': 10, 'c': 20}]
>>> dFrame = pd.DataFrame(listDict)
>>> dictForest = {'State': ['Assam', 'Delhi'], 'GArea': [78438, 1483]}
>>> dFrame = pd.DataFrame(dictForest)
>>> dFrame = pd.DataFrame({'Series1': seriesA, 'Series2': seriesB})
>>> ResultDF['Preeti'] = [89, 78, 76]
>>> ResultDF.loc['English'] = [85, 86, 83, 80, 90, 89]
Use axis=0 for rows and axis=1 for columns.
>>> ResultDF = ResultDF.drop('Science', axis=0) # Drops row
>>> ResultDF = ResultDF.drop(['Samridhi', 'Riya'], axis=1) # Drops columns
>>> ResultDF = ResultDF.rename({'Maths': 'Sub1'}, axis='index')
>>> ResultDF = ResultDF.rename({'Arnab': 'Student1'}, axis='columns')
>>> ResultDF.loc['Science'] # Accesses a row as a Series
>>> ResultDF.loc[:, 'Arnab'] # Accesses a column as a Series
>>> ResultDF.loc['Maths'] > 90
>>> ResultDF.loc['Maths':'Science', 'Arnab':'Samridhi']
The .append() method is used to append rows of one DataFrame to another.
Key Parameters:
>>> dFrame1 = dFrame1.append(dFrame2, ignore_index=True)
| Attribute | Purpose | Example Output |
|---|---|---|
| index | Displays row labels | Index(['GeoArea', 'VeryDense'], dtype='object') |
| columns | Displays column labels | Index(['Assam', 'Kerala'], dtype='object') |
| dtypes | Displays data type of each column | Assam: int64, Delhi: float64 |
| values | Returns values as a 2D NumPy ndarray | array([[78438, 38852], [2797, 1663]]) |
| shape | Returns a tuple representing dimensionality (rows, columns) | (4, 3) |
| size | Returns total number of elements | 12 |
| T | Transposes rows and columns | Swaps row indices with column headers |
The read_csv() function loads data from a CSV file into a DataFrame.
>>> marks = pd.read_csv("C:/NCERT/ResultData.csv", sep=",", header=0)
Parameters:
The to_csv() method writes a DataFrame to a CSV or \text file.
>>> ResultDF.to_csv('C:/NCERT/resultout.csv', sep=',', index=False)
Parameters:
| Feature | Pandas Series | NumPy ndarray |
|---|---|---|
| Index Type | Supports custom labelled indices (numbers or letters) | Accessed strictly by integer positions starting from 0 |
| Alignment | Automatically aligns data based on labels; generates NaN for mismatches | Requires matching shapes; operations fail if arrays are unaligned |
| Memory | Requires more memory due to index mapping metadata | Highly memory-efficient |