Python Data Science Sinhala Guide | NumPy, Pandas, Matplotlib Basics

ආයුබෝවන් කට්ටියට! 🖐️ අද කාලේ ලෝකේ තියෙන ලොකුම trends වලින් එකක් තමයි Data Science. හැම තැනම data, data analyze කරලා decisions ගන්න එක දැන් අත්යවශ්ය දෙයක් වෙලා. මේ Data Science කියන විශාල ලෝකයේ, Python කියන්නේ රජ කරන භාෂාවක් කිව්වොත් වැරදි නෑ. ඒකට හේතුව තමයි Python වල තියෙන powerful libraries ගොඩක්.
ඉතින්, අද අපි මේ tutorial එකෙන් බලන්න යන්නේ Python Data Science වල තියෙන අත්යාවශ්යම Libraries තුනක් ගැනයි: ඒ තමයි NumPy, Pandas, සහ Matplotlib/Seaborn. මේවා නැතුව Data Science කරන්න හිතන්නවත් බෑ! අලුතෙන් මේ field එකට එන අයට වගේම, දැනටමත් වැඩ කරන අයටත් මේ guide එක ගොඩක් ප්රයෝජනවත් වෙයි කියලා මම හිතනවා. අපි මේවා මොනවද, ඇයි මේවා වැදගත් වෙන්නේ, සහ කොහොමද practical විදියට භාවිතා කරන්නේ කියලා පැහැදිලි උදාහරණ එක්කම බලමු.
අවසානයේදී, පොඩි data set එකක් අරගෙන, ඒක මේ libraries ටික පාවිච්චි කරලා කොහොමද analyze කරන්නේ කියලාත් බලමු. එහෙනම්, අපි පටන් ගමුද?
NumPy – සංඛ්යාත්මක ගණනය කිරීම් වල කොඳු නාරටිය
මුලින්ම අපි බලමු NumPy (Numerical Python) ගැන. Data Science වලදි අපි වැඩ කරන්නේ ගොඩක් වෙලාවට numbers එක්ක. මේ numbers විශාල ප්රමාණයක් තියෙන්න පුළුවන් arrays (ආරේ) විදිහට. NumPy තමයි මේ වගේ multi-dimensional arrays efficiently manage කරන්නයි, ඒවට complex mathematical operations කරන්නයි උදව් කරන්නේ.
ඇයි NumPy වැදගත් වෙන්නේ?
- Speed: Python වල සාමාන්ය lists වලට වඩා NumPy arrays ගොඩක් වේගවත්. (C language එකෙන් implement කරලා තියෙන්නේ)
- Memory Efficiency: Data විශාල ප්රමාණයක් තියාගන්න වඩාත් කාර්යක්ෂමයි.
- Powerful Functions: Linear algebra, Fourier transforms, random number generation වගේ advanced mathematical functions ගොඩක් එකතු කරලා තියෙනවා.
NumPy Arrays හදමු සහ භාවිතා කරමු
NumPy වල ප්රධානම data structure එක තමයි ndarray
(n-dimensional array) එක. මේක සාමාන්ය Python list එකකට වඩා වෙනස්. අපි බලමු කොහොමද මේවා හදන්නේ සහ basic operations කරන්නේ කියලා.
import numpy as np
# Python list එකකින් NumPy array එකක් හදමු
my_list = [1, 2, 3, 4, 5]
numpy_array = np.array(my_list)
print("My NumPy Array:", numpy_array)
print("Type of array:", type(numpy_array))
print("Shape of array:", numpy_array.shape) # Array එකේ dimensions
# Zeroes වලින් array එකක් හදමු
zeros_array = np.zeros((3, 4)) # 3 rows, 4 columns
print("\nZeros Array:\n", zeros_array)
# Ones වලින් array එකක් හදමු
ones_array = np.ones((2, 3)) # 2 rows, 3 columns
print("\nOnes Array:\n", ones_array)
# Range එකක් අනුව array එකක් හදමු (arange)
range_array = np.arange(0, 10, 2) # 0 ඉඳලා 10ට (exclusive) 2න් 2ට
print("\nRange Array:", range_array)
# Random numbers වලින් array එකක් හදමු
random_array = np.random.randint(0, 100, size=(3, 3)) # 0-99 අතර random integers 3x3 matrix එකක්
print("\nRandom Array:\n", random_array)
# Array Operations
array1 = np.array([10, 20, 30, 40])
array2 = np.array([1, 2, 3, 4])
# එකතු කිරීම
sum_array = array1 + array2
print("\nSum of arrays:", sum_array)
# ගුණ කිරීම (Element-wise multiplication)
product_array = array1 * array2
print("Product of arrays:", product_array)
# Scalar operations
scaled_array = array1 * 2
print("Scaled array:", scaled_array)
# Slicing and Indexing
print("\nFirst element:", numpy_array[0])
print("Elements from index 1 to 3:", numpy_array[1:4])
print("Last element:", numpy_array[-1])
# Multi-dimensional array slicing
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print("\nMatrix:\n", matrix)
print("First row:", matrix[0])
print("Second row, third column:", matrix[1, 2]) # 5
print("All rows, second column:", matrix[:, 1]) # [2, 5, 8]
දැක්කනේ? NumPy array කියන්නේ කොයි තරම් පහසුද කියලා! මේවා තමයි Pandas වල DataFrames වලටත් foundation එක වෙන්නේ.
Pandas – Data Manipulation වල මාස්ටර්
NumPy වලින් අපි සංඛ්යාත්මක data එක්ක වැඩ කරන හැටි ඉගෙන ගත්තා. හැබැයි real-world data කියන්නේ numbers විතරක් නෙවෙයි. Text, dates, missing values වගේ දේවලුත් තියෙනවා. මේ හැමදේම එකට අරගෙන, පහසුවෙන් organize කරලා, analyze කරන්න Pandas කියන library එක ගොඩක් ප්රයෝජනවත් වෙනවා.
ඇයි Pandas වැදගත් වෙන්නේ?
- Data Structures: Pandas වල ප්රධානම data structures දෙකක් තියෙනවා: Series (එක් dimension එකක් තියෙන array එකක් වගේ) සහ DataFrame (වගුවක් වගේ, rows සහ columns තියෙන data structure එකක්).
- Data Handling: Missing data, filtering, grouping, merging වගේ complex data operations පහසුවෙන් කරන්න පුළුවන්.
- File I/O: CSV, Excel, SQL databases වගේ විවිධ format වලින් data load කරන්න සහ save කරන්න පුළුවන්.
Pandas DataFrame එකක් හදමු සහ භාවිතා කරමු
අපි බලමු කොහොමද DataFrame එකක් හදන්නේ, ඒකට data load කරන්නේ, සහ basic manipulation කරන්නේ කියලා.
import pandas as pd
import numpy as np # NumPyත් import කරගන්නවා Pandas එක්ක වැඩ කරන්න
# Dictionary එකකින් DataFrame එකක් හදමු
data = {
'Name': ['Amal', 'Kamala', 'Sunil', 'Nimal', 'Saman'],
'Age': [25, 30, 22, 35, 28],
'City': ['Colombo', 'Kandy', 'Galle', 'Colombo', 'Matara'],
'Salary': [50000, 75000, 45000, 90000, 60000]
}
df = pd.DataFrame(data)
print("Our first DataFrame:\n", df)
# CSV file එකකින් Data Load කරමු (අපිට file එකක් නැති නිසා, dummy එකක් හදාගමු)
# df.to_csv('sample_data.csv', index=False) # මේක run කරාම file එකක් හැදෙනවා
# CSV file එකකින් DataFrame එකක් Load කරන හැටි
# dummy_df = pd.read_csv('sample_data.csv')
# print("\nDataFrame loaded from CSV:\n", dummy_df)
# DataFrame එකේ මුල් rows ටික බලමු
print("\nFirst 3 rows:\n", df.head(3))
# DataFrame එකේ අන්තිම rows ටික බලමු
print("\nLast 2 rows:\n", df.tail(2))
# DataFrame එකේ information (data types, non-null counts)
print("\nDataFrame Info:")
df.info()
# Basic statistics බලමු (mean, min, max, std dev)
print("\nBasic Statistics:\n", df.describe())
# Columns select කරමු
print("\nNames column:\n", df['Name'])
print("\nName and Age columns:\n", df[['Name', 'Age']])
# Rows filter කරමු (Age 30ට වැඩිය අය)
print("\nPeople older than 30:\n", df[df['Age'] > 30])
# එකට filters දෙකක්
print("\nPeople from Colombo & Age > 25:\n", df[(df['City'] == 'Colombo') & (df['Age'] > 25)])
# නව Column එකක් එකතු කරමු
df['Bonus'] = df['Salary'] * 0.10 # 10% bonus
print("\nDataFrame with Bonus column:\n", df)
# Column එකක් drop කරමු
# df_no_bonus = df.drop(columns=['Bonus'])
# print("\nDataFrame without Bonus column:\n", df_no_bonus)
# Grouping and Aggregation
# City අනුව salaries වල average එක
avg_salary_by_city = df.groupby('City')['Salary'].mean()
print("\nAverage Salary by City:\n", avg_salary_by_city)
දැන් ඔයාලට පේනවා ඇති Pandas වලින් data manipulate කරන එක කොච්චර පහසුද කියලා. Real-world data sets වලදි මේ වගේ operations දහස් ගණනක් කරන්න වෙනවා. එතකොට Pandas නැතුව මේක කරන්න අමාරුයි.
Matplotlib සහ Seaborn – Data Visualize කරමු
Data analyze කරලා numbers ටිකක් බැලුවට වැඩක් නෑ, ඒකෙන් අපිට පේන patterns, trends අනිත් අයටත් තේරුම් ගන්න පුළුවන් විදියට visualize කරලා පෙන්නන්න බැරිනම්. මෙතනදී තමයි Matplotlib සහ Seaborn කියන libraries දෙක අපිට උදව් කරන්නේ.
ඇයි Data Visualization වැදගත් වෙන්නේ?
- Understanding Patterns: Data වල තියෙන patterns, outliers, trends එකපාරටම හඳුනාගන්න පුළුවන්.
- Communication: Complex data insights සරලව අනිත් අයට communicate කරන්න පුළුවන්.
- Decision Making: වඩා හොඳ, data-driven decisions ගන්න උදව් වෙනවා.
Matplotlib – Basic Plotting
Matplotlib කියන්නේ Python වල තියෙන ප්රධානම plotting library එක. මේක ටිකක් low-level එකෙන් වැඩ කරන නිසා, අපිට plot එකේ හැම detail එකක්ම customize කරන්න පුළුවන්.
import matplotlib.pyplot as plt
import pandas as pd # DataFrames හදාගන්න
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 5, 4, 6]
# Line plot එකක් අඳිමු
plt.figure(figsize=(8, 5)) # Plot එකේ size එක adjust කරමු
plt.plot(x, y, marker='o', linestyle='-', color='blue') # Line plot එක අඳිනවා
plt.title('Simple Line Plot') # Title එක
plt.xlabel('X-axis Label') # X-axis ලේබල් එක
plt.ylabel('Y-axis Label') # Y-axis ලේබල් එක
plt.grid(True) # Grid එකක් එකතු කරමු
plt.show() # Plot එක display කරමු
# Scatter plot එකක්
plt.figure(figsize=(8, 5))
plt.scatter(x, y, color='red', marker='x')
plt.title('Simple Scatter Plot')
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.show()
Seaborn – Beautiful Statistical Plots
Matplotlib වලට උඩින් හදලා තියෙන library එකක් තමයි Seaborn කියන්නේ. මේකෙන් Matplotlib වලට වඩා ලස්සන, statistic plots හදන්න පුළුවන්. ඒ වගේම Pandas DataFrames එක්ක ගොඩක් හොඳට වැඩ කරනවා.
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Pandas DataFrame එකක් පාවිච්චි කරමු
data = {
'Name': ['Amal', 'Kamala', 'Sunil', 'Nimal', 'Saman', 'Tharindu', 'Priya'],
'Age': [25, 30, 22, 35, 28, 40, 29],
'City': ['Colombo', 'Kandy', 'Galle', 'Colombo', 'Matara', 'Kandy', 'Galle'],
'Salary': [50000, 75000, 45000, 90000, 60000, 110000, 55000]
}
df = pd.DataFrame(data)
plt.figure(figsize=(10, 6))
# Age distribution එක බලන්න Histogram එකක් අඳිමු
sns.histplot(df['Age'], bins=5, kde=True) # kde=True density estimation එකත් පෙන්නනවා
plt.title('Distribution of Age')
plt.xlabel('Age')
plt.ylabel('Count')
plt.show()
plt.figure(figsize=(10, 6))
# City එක අනුව Average Salary එක Bar plot එකකින් බලමු
sns.barplot(x='City', y='Salary', data=df, estimator=np.mean)
plt.title('Average Salary by City')
plt.xlabel('City')
plt.ylabel('Average Salary')
plt.show()
plt.figure(figsize=(10, 6))
# Age සහ Salary අතර සම්බන්ධය Scatter plot එකකින් බලමු
sns.scatterplot(x='Age', y='Salary', data=df, hue='City', size='Salary', sizes=(20, 400))
plt.title('Age vs Salary by City')
plt.xlabel('Age')
plt.ylabel('Salary')
plt.show()
Seaborn එක්ක වැඩ කරනකොට diagrams කොච්චර ලස්සනට එනවද කියලා පේනවා නේද? මේ libraries දෙකම එකට පාවිච්චි කරලා අපිට ඕනම විදිහේ visualization එකක් හදාගන්න පුළුවන්.
පොඩි Data Analysis Workflow එකක්
දැන් අපි NumPy, Pandas, Matplotlib/Seaborn කියන Libraries තුනම වෙන වෙනම ඉගෙන ගත්තනේ. දැන් බලමු මේවා එකට පාවිච්චි කරලා පොඩි Data Analysis Workflow එකක් කොහොමද කරන්නේ කියලා. අපි හිතමු අපිට studentsලා ටිකකගේ marks analyze කරන්න ඕන කියලා.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# 1. Data එක Load කරමු (Pandas)
# අපි පොඩි dictionary එකකින් DataFrame එකක් හදාගමු
student_data = {
'Student_ID': [101, 102, 103, 104, 105, 106, 107, 108, 109, 110],
'Subject_A': [75, 88, 62, 91, 78, 85, 70, 95, 68, 80],
'Subject_B': [80, 75, 70, 85, 90, 78, 65, 92, 72, 88],
'Subject_C': [60, 92, 55, 88, 70, 80, 72, 90, 65, 75],
'Attendance_Percentage': [90, 95, 80, 98, 85, 92, 75, 99, 82, 88]
}
students_df = pd.DataFrame(student_data)
print("Original Student Data:\n", students_df)
# 2. Data Explore කරමු / Clean කරමු (Pandas)
# Missing values බලමු
print("\nMissing Values:\n", students_df.isnull().sum()) # මේකේ නම් missing values නෑ
# Basic statistics
print("\nDescriptive Statistics for Marks:\n", students_df[['Subject_A', 'Subject_B', 'Subject_C']].describe())
# 3. නව Features හදමු (Pandas & NumPy)
# Total Marks
students_df['Total_Marks'] = students_df['Subject_A'] + students_df['Subject_B'] + students_df['Subject_C']
# Average Marks
students_df['Average_Marks'] = students_df['Total_Marks'] / 3
# Pass/Fail status (අපි හිතමු Average Marks 70ට වැඩි නම් Pass කියලා)
students_df['Status'] = np.where(students_df['Average_Marks'] >= 70, 'Pass', 'Fail')
print("\nStudent Data with Total, Average Marks and Status:\n", students_df)
# 4. Data Visualize කරමු (Matplotlib & Seaborn)
# Average Marks Distribution
plt.figure(figsize=(10, 6))
sns.histplot(students_df['Average_Marks'], bins=5, kde=True)
plt.title('Distribution of Average Marks')
plt.xlabel('Average Marks')
plt.ylabel('Number of Students')
plt.show()
# Pass/Fail Count
plt.figure(figsize=(7, 5))
sns.countplot(x='Status', data=students_df, palette='viridis')
plt.title('Pass/Fail Count')
plt.xlabel('Status')
plt.ylabel('Number of Students')
plt.show()
# Relationship between Attendance and Average Marks
plt.figure(figsize=(10, 6))
sns.scatterplot(x='Attendance_Percentage', y='Average_Marks', data=students_df, hue='Status', size='Total_Marks', sizes=(50, 500))
plt.title('Attendance vs Average Marks')
plt.xlabel('Attendance Percentage')
plt.ylabel('Average Marks')
plt.grid(True)
plt.show()
# Subject wise average marks
subject_avg = students_df[['Subject_A', 'Subject_B', 'Subject_C']].mean()
plt.figure(figsize=(8, 5))
sns.barplot(x=subject_avg.index, y=subject_avg.values, palette='magma')
plt.title('Average Marks per Subject')
plt.xlabel('Subject')
plt.ylabel('Average Marks')
plt.ylim(50, 100) # Y-axis limit එකක් දාමු
plt.show()
print("\nAnalysis Complete! We can see patterns like:")
print(f"- Overall average mark is: {students_df['Average_Marks'].mean():.2f}")
print(f"- Number of Passed students: {students_df[students_df['Status'] == 'Pass'].shape[0]}")
print(f"- Number of Failed students: {students_df[students_df['Status'] == 'Fail'].shape[0]}")
print("- Attendance seems to have a positive correlation with Average Marks.")
දැක්කනේ කොහොමද මේ libraries තුන එකට එකතු කරලා පොඩි data set එකක් analyze කරන්නේ කියලා? මේක ගොඩක් basic උදාහරණයක් වුණාට, real-world data sets වලදිත් ඔයාලා මේ වගේ steps ටික තමයි follow කරන්න වෙන්නේ.
නිගමනය (Conclusion)
ඉතින් කට්ටිය, අපි අද Python for Data Science වල තියෙන අත්යවශ්යම Libraries තුනක් ගැන ගොඩක් දේවල් ඉගෙන ගත්තා. NumPy වලින් සංඛ්යාත්මක data එක්ක efficiently වැඩ කරන්න පුළුවන් හැටි දැක්කා. Pandas වලින් data manipulate කරන, analyze කරන විවිධ ක්රම අපි සාකච්ඡා කළා. අන්තිමට, Matplotlib සහ Seaborn පාවිච්චි කරලා data visualizations කොහොමද ලස්සනට හදන්නේ කියලාත් අපි බැලුවා.
මේ libraries තුන ඕනෑම Data Scientist කෙනෙක්ට නැතුවම බැරි tools ටිකක්. මේවා හොඳට ඉගෙන ගත්තොත්, ඕනෑම data set එකක් අරගෙන ඒකෙන් තේරුමක් තියෙන insights ගන්න ඔයාලට පුළුවන් වෙනවා. මතක තියාගන්න, coding කියන්නේ කරලම ඉගෙන ගන්න ඕන දෙයක්. ඉතින්, මේ උදාහරණ ටික ඔයාලගේ computer එකේ run කරලා බලන්න. පොඩි පොඩි වෙනස්කම් කරලා බලන්න. ඔයාලගේම පොඩි data set එකක් අරගෙන analyze කරන්න උත්සාහ කරන්න.
මේ ගැන ඔයාලට තියෙන අදහස්, ප්රශ්න, අත්දැකීම් පහළ Comments section එකේ දාන්න අමතක කරන්න එපා. අපි එකට ඉගෙන ගමු, එකට දියුණු වෙමු! 😊 තවත් මේ වගේ ප්රයෝජනවත් tutorial එකකින් හමුවෙමු!