0% found this document useful (0 votes)
20 views16 pages

ML IU48prac1,2

The document outlines practical exercises using Python libraries such as Numpy, Pandas, and Matplotlib. It includes code examples for creating and manipulating arrays and data frames, as well as visualizing data through various plots. The exercises cover basic operations, file reading, data manipulation, and chart plotting techniques.

Uploaded by

mevadakevin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views16 pages

ML IU48prac1,2

The document outlines practical exercises using Python libraries such as Numpy, Pandas, and Matplotlib. It includes code examples for creating and manipulating arrays and data frames, as well as visualizing data through various plots. The exercises cover basic operations, file reading, data manipulation, and chart plotting techniques.

Uploaded by

mevadakevin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Practical - 1

AIM: Study of Python Basic Libraries like a Numpy. Perform the following task
using Numpy library.

Code 1 : Creating blank array, with predefined data, with pattern specific data
import numpy as np
a = np.array([])
b = np.array([1, 2, 3, 4])
c = np.arange(0, 11, 2)
print("Blank Array: ", a)
print("Predefined Array: ", b)
print("Array containing even numbers: ", c)

Output 1:
Blank Array: []
Predefined Array: [1 2 3 4]
Array containing even numbers: [ 0 2 4 6 8 10]

Code 2 : Slicing and Updating elements


import numpy as np
a = np.array([1, 2, 3, 4, 5])
print("Original Array: ", a)
b = a[:4]
print("Spliced Array: ", b)
a[:2] = 0
print("Updated Array: ", a)

Output 2:
Original Array: [1 2 3 4 5]
Spliced Array: [1 2 3 4]
Updated Array: [0 0 3 4 5]

Code 3: Shape manipulations


import numpy as np
a = np.array([1, 2, 3, 4])
print("Original Array: ", a)
b = np.reshape(a, (2, 2))
print("Reshaped Array: ", b)
c = b.flatten()
print("Flattened Array:
", c)

IU21412300048 7CSE-A1 1
Machine Learning(CS0701)
d = np.transpose(b)
print("Transpose: ", d)

Output 3:
Original Array: [1 2 3 4]
Reshaped Array: [[1 2]
[3 4]]
Flattened Array: [1 2 3 4]
Transpose: [[1 3]
[2 4]]

Code 4 : Looping over arrays


import numpy as np
a = np.array([[1, 2], [3, 4]])
for r in a:
for i in r:
print(i)

Output 4 :

1
2
3
4

Code 5 : Reading files in NumPy


import numpy as np
a = np.loadtxt('/content/ML1.TXT')
print(a)

Output 5 :
[1. 2. 3. 4. 5. 6.]

IU21412300048 7CSE-A1 2
Practical - 2

AIM: Study of Python Libraries for ML applications such as Pandas and Matplotlib
Perform the following task using Pandas & Matplotlib library.

Pandas
Code 1 : Creating data frame
import pandas as pd

def create_dataframe():
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Age': [24, 27, 22, 32, 29],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix']
}
df = pd.DataFrame(data)
print("DataFrame:\n", df)
return df

df = create_dataframe()

Output 1:
DataFrame:
Name Age City
0 Alice 24 New York
1 Bob 27 Los Angeles
2 Charlie 22 Chicago
3 David 32 Houston
4 Eve 29 Phoenix

Code 2 : Reading files


import pandas as pd

def read_file(file_path):
df = pd.read_csv(file_path)
print("\nDataFrame from file:\n", df)
file_path = '/content/industry.csv'
read_file(file_path)

Output 2:

DataFrame from file:

IU21412300048 7CSE-A1 3
Industry
0 Accounting/Finance
1 Advertising/Public Relations
2 Aerospace/Aviation
3 Arts/Entertainment/Publishing
4 Automotive
5 Banking/Mortgage
6 Business Development
7 Business Opportunity
8 Clerical/Administrative
9 Construction/Facilities
10 Consumer Goods
11 Customer Service
12 Education/Training
13 Energy/Utilities
14 Engineering
15 Government/Military
16 Green
17 Healthcare
18 Hospitality/Travel
19 Human Resources

Code 3: Slicing manipulations


import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Age': [24, 27, 22, 32, 29],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix']

df = pd.DataFrame(data)
sliced_df = df.iloc[0:3]
print("\nSliced DataFrame (rows 0 to 2):\n", sliced_df)

Output 3:
Sliced DataFrame (rows 0 to 2):
Name Age City
0 Alice 24 New York
1 Bob 27 Los Angeles
2 Charlie 22 Chicago

Code 4 : Exporting data to files


import pandas as pd
def read_and_print_csv(file_path):
df = pd.read_csv(file_path)
print("\nDataFrame from file:\n", df)
file_path =
'/content/industry.csv'

IU21412300048 7CSE-A1 4
Machine Learning(CS0701)
read_and_print_csv(file_path)

Output 4 :
DataFrame from file:
Name Age City
0 Alice 24 New York
1 Bob 27 Los Angeles
2 Charlie 22 Chicago
3 David 32 Houston
4 Eve 29 Phoenix

Code 5 : Columns and row manipulations with loops


import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Age': [24, 27, 22, 32, 29],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix']
}
df = pd.DataFrame(data)
for index, row in df.iterrows():
df.at[index, 'Age in 5 Years'] = row['Age'] + 5
for index, row in df.iterrows():
df.at[index, 'City'] = row['City'].upper()
print("\nDataFrame after manipulations:\n", df)

Output 5 :
DataFrame after manipulations:
Name Age City Age in 5 Years
0 Alice 24 NEW YORK 29.0
1 Bob 27 LOS ANGELES 32.0
2 Charlie 22 CHICAGO 27.0
3 David 32 HOUSTON 37.0
4 Eve 29 PHOENIX 34.0

Code 6 : Use pandas for masking data and reading in Boolean format.
import pandas as pd

data = {

'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],

'Age': [24, 27, 22, 32, 29],

'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix']

df = pd.DataFrame(data)

IU21412300048 7CSE-A1 5
Machine Learning(CS0701)
mask = df['Age'] > 25

masked_df = df[mask]

print("\nBoolean mask:\n", mask)

print("\nFiltered DataFrame (Age > 25):\n", masked_df)


Output 6 :
Boolean mask:
0False
1True
2False

3 True
4 True
Name: Age, dtype: bool
Filtered DataFrame (Age > 25):
Name Age City
1 Bob27 Los Angeles
3 David32 Houston
4 Eve29 Phoenix

Matplotlib
Code 1 : Importing
matplotlib
Simple line chart
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1,3,5,7])
y = x*2
plt.plot(x, y)
plt.show()

Output 1:

IU21412300048 7CSE-A1 6
Machine Learning(CS0701)

Code 2 : Correlation chart


import pandas as p
import numpy as n
import matplotlib. pyplot as pt
var1 = p. Series ([1, 3, 4, 6, 7, 9])
var2 = p. Series ([2, 4, 7, 8, 9, 11])
pt. scatter (var1, var2)
pt. plot (n. unique (var1), n. poly1d (n. polyfit (var1, var2, 1))(n. unique
(var1)), color = 'green')

Output 2:

Code 3: Histogram
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randint(20,150,60)
plt.hist(x)
plt.show()

Output 3:

IU21412300048 7CSE-A1 7
Machine Learning(CS0701)

Code 4 : Plotting of Multivariate data


import numpy as np
import matplotlib.pyplot as plt
np.random.seed(2)
x, y = np.random.randn(2, 30)
y *= 100
z = 11*x + 3.4*y - 4 + np.random.randn(30) ##the model
fig, ax = plt.subplots()
scat = ax.scatter(x, y, c=z, s=200, marker='o')
fig.colorbar(scat)
plt.show()

Output 4 :

Code 5 : Plot Pi Chart


import matplotlib.pyplot as plt
import numpy as np
y = np.array([25, 35, 15, 5])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
myexplode = [0.2, 0, 0, 0]
plt.pie(y, labels = mylabels, explode = myexplode, shadow = True)
plt.legend()
plt.show()

Output 5 :

IU21412300048 7CSE-A1 8

You might also like