Galle, LK--:--5/6 sites live

Complete Pandas Tutorial in Python

අවුල් සහගත CSV file එකක්, model එකකට ඉගෙන ගන්න පුළුවන් දෙයක් බවට හරවන tool එක තමයි Pandas. සැබෑ ML projects ගොඩක් පටන් ගන්නෙ model එකෙන් නෙවෙයි, මෙතනින්.

Pandas is the tool that turns a messy CSV file into something a model can actually learn from. Almost every real ML project starts here, not with the model.

4 May 202611 min readSelf Guide · Stage 13#Python & Data Basics#Python Libraries#Machine learning

Lesson 10 of 64 · Part 1 · Python & Data Basics · Python Libraries · bilingual notes (English + සිංහල)

Why this matters. Pandas is the tool that turns a messy CSV file into something a model can actually learn from. Almost every real ML project starts here, not with the model.

සිංහලෙන්: අවුල් සහගත CSV file එකක්, model එකකට ඉගෙන ගන්න පුළුවන් දෙයක් බවට හරවන tool එක තමයි Pandas. සැබෑ ML projects ගොඩක් පටන් ගන්නෙ model එකෙන් නෙවෙයි, මෙතනින්.

What you'll use this for. You will use read_csv, .head(), .describe(), and .dropna() in literally every single project notebook from here on.

සිංහලෙන්: read_csv, .head(), .describe(), .dropna() — මේ ඔක්කොම මින් ඉස්සරහට එන හැම project notebook එකකම පාවිච්චි වෙනවා.

Key principles

  • A DataFrame is a spreadsheet Python can compute on. Rows are records (one patient, one house), columns are features (age, price) — the exact shape scikit-learn expects.
    DataFrame එකක් කියන්නෙ Python එකට calculate කරන්න පුළුවන් spreadsheet එකක්
  • Real data is never clean — that's the whole point of this lesson. Missing values, wrong types, duplicate rows — Pandas gives you .isnull(), .fillna(), .drop_duplicates() to fix all of it before it reaches your model.
    සැබෑ data කවදාවත් පිරිසිදු නෑ — මේ පාඩමේ මුළු අදහසම ඒකයි

Walkthrough

Pandas Library:

Useful for Data Processing & Analysis

Pandas Data Frame:

Pandas DataFrame is two-dimensional tabular data structure with labeled axes (rows and columns).

ExamplePython
# importing the pandas library
import pandas as pd
import numpy as np

Creaating a Pandas DataFrame

ExamplePython
# importing the boston house price data
from sklearn.datasets import load_boston
ExamplePython
boston_dataset = load_boston()
ExamplePython
type(boston_dataset)

Output

Output
sklearn.utils.Bunch
ExamplePython
print(boston_dataset)

Output

Output
{'data': array([[6.3200e-03, 1.8000e+01, 2.3100e+00, ..., 1.5300e+01, 3.9690e+02,
        4.9800e+00],
       [2.7310e-02, 0.0000e+00, 7.0700e+00, ..., 1.7800e+01, 3.9690e+02,
        9.1400e+00],
       [2.7290e-02, 0.0000e+00, 7.0700e+00, ..., 1.7800e+01, 3.9283e+02,
        4.0300e+00],
       ...,
       [6.0760e-02, 0.0000e+00, 1.1930e+01, ..., 2.1000e+01, 3.9690e+02,
        5.6400e+00],
       [1.0959e-01, 0.0000e+00, 1.1930e+01, ..., 2.1000e+01, 3.9345e+02,
        6.4800e+00],
       [4.7410e-02, 0.0000e+00, 1.1930e+01, ..., 2.1000e+01, 3.9690e+02,
        7.8800e+00]]), 'target': array([24. , 21.6, 34.7, 33.4, 36.2, 28.7, 22.9, 27.1, 16.5, 18.9, 15. ,
       18.9, 21.7, 20.4, 18.2, 19.9, 23.1, 17.5, 20.2, 18.2, 13.6, 19.6,
       15.2, 14.5, 15.6, 13.9, 16.6, 14.8, 18.4, 21. , 12.7, 14.5, 13.2,
       13.1, 13.5, 18.9, 20. , 21. , 24.7, 30.8, 34.9, 26.6, 25.3, 24.7,
       21.2, 19.3, 20. , 16.6, 14.4, 19.4, 19.7, 20.5, 25. , 23.4, 18.9,
       35.4, 24.7, 31.6, 23.3, 19.6, 18.7, 16. , 22.2, 25. , 33. , 23.5,
… (41 more lines)
ExamplePython
# pandas DataFrame
boston_df = pd.DataFrame(boston_dataset.data, columns = boston_dataset.feature_names)
ExamplePython
boston_df.head()
CRIMZNINDUSCHASNOXRMAGE…
00.0063218.02.310.00.5386.57565.2…
10.027310.07.070.00.4696.42178.9…
20.027290.07.070.00.4697.18561.1…
30.032370.02.180.00.4586.99845.8…
40.069050.02.180.00.4587.14754.2…
ExamplePython
boston_df.shape

Output

Output
(506, 13)
ExamplePython
type(boston_df)

Output

Output
pandas.core.frame.DataFrame

Importing the data from a CSV file to a pandas DataFrame

ExamplePython
# csv file to pandas df
diabetes_df = pd.read_csv('/content/diabetes.csv')
ExamplePython
type(diabetes_df)

Output

Output
pandas.core.frame.DataFrame
ExamplePython
diabetes_df.head()
PregnanciesGlucoseBloodPressureSkinThicknessInsulinBMIDiabetesPedigreeFunction…
061487235033.60.627…
11856629026.60.351…
28183640023.30.672…
318966239428.10.167…
40137403516843.12.288…
ExamplePython
diabetes_df.shape

Output

Output
(768, 9)

Loading the data from a excel file to a Pandas DataFrame:

pd.read_excel('file path')

Exporting a DataFrame to a csv file

ExamplePython
boston_df.to_csv('boston.csv')

Exporting the Pandas DataFrame to an excel File:

df.to_excel('filename')

ExamplePython
# creating a DatFrame with random values
random_df = pd.DataFrame(np.random.rand(20,10))
ExamplePython
random_df.head()
0123456…
00.9785860.7984570.7560650.5745590.7314370.9763970.865563…
10.0787770.2955960.6084080.3100860.3261990.0866000.549180…
20.1728730.9711980.5921910.4829040.1716010.9817570.268020…
30.8122120.6124940.0114460.8170390.0768370.7128910.929890…
40.6293190.0463470.9181800.3173850.6924540.7938900.016952…
ExamplePython
random_df.shape

Output

Output
(20, 10)

Inspecting a DataFrame

ExamplePython
#finding the number of rows & columns
boston_df.shape

Output

Output
(506, 13)
ExamplePython
# first 5 rows in a DataFrame
boston_df.head()
CRIMZNINDUSCHASNOXRMAGE…
00.0063218.02.310.00.5386.57565.2…
10.027310.07.070.00.4696.42178.9…
20.027290.07.070.00.4697.18561.1…
30.032370.02.180.00.4586.99845.8…
40.069050.02.180.00.4587.14754.2…
ExamplePython
# last 5 rows of the DataFrame
boston_df.tail()
CRIMZNINDUSCHASNOXRMAGE…
5010.062630.011.930.00.5736.59369.1…
5020.045270.011.930.00.5736.12076.7…
5030.060760.011.930.00.5736.97691.0…
5040.109590.011.930.00.5736.79489.3…
5050.047410.011.930.00.5736.03080.8…
ExamplePython
# informations about the DataFrame
boston_df.info()

Output

Output
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 506 entries, 0 to 505
Data columns (total 13 columns):
 #   Column   Non-Null Count  Dtype  
---  ------   --------------  -----  
 0   CRIM     506 non-null    float64
 1   ZN       506 non-null    float64
 2   INDUS    506 non-null    float64
 3   CHAS     506 non-null    float64
 4   NOX      506 non-null    float64
 5   RM       506 non-null    float64
 6   AGE      506 non-null    float64
 7   DIS      506 non-null    float64
 8   RAD      506 non-null    float64
 9   TAX      506 non-null    float64
 10  PTRATIO  506 non-null    float64
 11  B        506 non-null    float64
 12  LSTAT    506 non-null    float64
… (2 more lines)
ExamplePython
# finding the number of missing values
boston_df.isnull().sum()

Output

Output
CRIM       0
ZN         0
INDUS      0
CHAS       0
NOX        0
RM         0
AGE        0
DIS        0
RAD        0
TAX        0
PTRATIO    0
B          0
LSTAT      0
dtype: int64
ExamplePython
# diabetes dataframe
diabetes_df.head()
PregnanciesGlucoseBloodPressureSkinThicknessInsulinBMIDiabetesPedigreeFunction…
061487235033.60.627…
11856629026.60.351…
28183640023.30.672…
318966239428.10.167…
40137403516843.12.288…
ExamplePython
# counting the values based on the labels
diabetes_df.value_counts('Outcome')

Output

Output
Outcome
0    500
1    268
dtype: int64
ExamplePython
# group the values based on the mean
diabetes_df.groupby('Outcome').mean()
PregnanciesGlucoseBloodPressureSkinThicknessInsulinBMIDiabetesPedigreeFunctionAge
Outcome
03.298000109.98000068.18400019.66400068.79200030.3042000.42973431.190000
14.865672141.25746370.82462722.164179100.33582135.1425370.55050037.067164

Statistical Measures

ExamplePython
# count or number of values
boston_df.count()

Output

Output
CRIM       506
ZN         506
INDUS      506
CHAS       506
NOX        506
RM         506
AGE        506
DIS        506
RAD        506
TAX        506
PTRATIO    506
B          506
LSTAT      506
dtype: int64
ExamplePython
# mean value - column wise
boston_df.mean()

Output

Output
CRIM         3.613524
ZN          11.363636
INDUS       11.136779
CHAS         0.069170
NOX          0.554695
RM           6.284634
AGE         68.574901
DIS          3.795043
RAD          9.549407
TAX        408.237154
PTRATIO     18.455534
B          356.674032
LSTAT       12.653063
dtype: float64
ExamplePython
# standard deviation - column wise
boston_df.std()

Output

Output
CRIM         8.601545
ZN          23.322453
INDUS        6.860353
CHAS         0.253994
NOX          0.115878
RM           0.702617
AGE         28.148861
DIS          2.105710
RAD          8.707259
TAX        168.537116
PTRATIO      2.164946
B           91.294864
LSTAT        7.141062
dtype: float64
ExamplePython
# minimum value
boston_df.min()

Output

Output
CRIM         0.00632
ZN           0.00000
INDUS        0.46000
CHAS         0.00000
NOX          0.38500
RM           3.56100
AGE          2.90000
DIS          1.12960
RAD          1.00000
TAX        187.00000
PTRATIO     12.60000
B            0.32000
LSTAT        1.73000
dtype: float64
ExamplePython
# maximum value
boston_df.max()

Output

Output
CRIM        88.9762
ZN         100.0000
INDUS       27.7400
CHAS         1.0000
NOX          0.8710
RM           8.7800
AGE        100.0000
DIS         12.1265
RAD         24.0000
TAX        711.0000
PTRATIO     22.0000
B          396.9000
LSTAT       37.9700
dtype: float64
ExamplePython
# all the statistical measures about the dataframe
boston_df.describe()
CRIMZNINDUSCHASNOXRMAGE…
count506.000000506.000000506.000000506.000000506.000000506.000000506.000000…
mean3.61352411.36363611.1367790.0691700.5546956.28463468.574901…
std8.60154523.3224536.8603530.2539940.1158780.70261728.148861…
min0.0063200.0000000.4600000.0000000.3850003.5610002.900000…
25%0.0820450.0000005.1900000.0000000.4490005.88550045.025000…
50%0.2565100.0000009.6900000.0000000.5380006.20850077.500000…

… 2 more rows

Manipulating a DataFrame

ExamplePython
# adding a column to a dataframe
boston_df['Price'] = boston_dataset.target
ExamplePython
boston_df.head()
CRIMZNINDUSCHASNOXRMAGE…
00.0063218.02.310.00.5386.57565.2…
10.027310.07.070.00.4696.42178.9…
20.027290.07.070.00.4697.18561.1…
30.032370.02.180.00.4586.99845.8…
40.069050.02.180.00.4587.14754.2…
ExamplePython
# removing a row
boston_df.drop(index=0, axis=0)
CRIMZNINDUSCHASNOXRMAGE…
10.027310.07.070.00.4696.42178.9…
20.027290.07.070.00.4697.18561.1…
30.032370.02.180.00.4586.99845.8…
40.069050.02.180.00.4587.14754.2…
50.029850.02.180.00.4586.43058.7…
........................…

… 5 more rows

ExamplePython
# drop a column
boston_df.drop(columns='ZN', axis=1)
CRIMINDUSCHASNOXRMAGEDIS…
00.006322.310.00.5386.57565.24.0900…
10.027317.070.00.4696.42178.94.9671…
20.027297.070.00.4697.18561.14.9671…
30.032372.180.00.4586.99845.86.0622…
40.069052.180.00.4587.14754.26.0622…
........................…

… 5 more rows

ExamplePython
# locating a row using the index value
boston_df.iloc[2]

Output

Output
CRIM         0.02729
ZN           0.00000
INDUS        7.07000
CHAS         0.00000
NOX          0.46900
RM           7.18500
AGE         61.10000
DIS          4.96710
RAD          2.00000
TAX        242.00000
PTRATIO     17.80000
B          392.83000
LSTAT        4.03000
Price       34.70000
Name: 2, dtype: float64
ExamplePython
# locating a particular column
print(boston_df.iloc[:,0])  # first column
print(boston_df.iloc[:,1])  # second column
print(boston_df.iloc[:,2])  # third column
print(boston_df.iloc[:,-1]) # last column

Output

Output
0      0.00632
1      0.02731
2      0.02729
3      0.03237
4      0.06905
        ...   
501    0.06263
502    0.04527
503    0.06076
504    0.10959
505    0.04741
Name: CRIM, Length: 506, dtype: float64
0      18.0
1       0.0
2       0.0
3       0.0
4       0.0
       ... 
… (30 more lines)

Correlation:

  1. Positive Correlation
  2. Negative Correlation
ExamplePython
boston_df.corr()
CRIMZNINDUSCHASNOXRMAGE…
CRIM1.000000-0.2004690.406583-0.0558920.420972-0.2192470.352734…
ZN-0.2004691.000000-0.533828-0.042697-0.5166040.311991-0.569537…
INDUS0.406583-0.5338281.0000000.0629380.763651-0.3916760.644779…
CHAS-0.055892-0.0426970.0629381.0000000.0912030.0912510.086518…
NOX0.420972-0.5166040.7636510.0912031.000000-0.3021880.731470…
RM-0.2192470.311991-0.3916760.091251-0.3021881.000000-0.240265…

… 8 more rows


Keep going: ← Lesson 9 · Lesson 11 → · Track it in the Self Guide