Ahsham.ml file
Ahsham.ml file
Practical No – 2.1
Aim - Write a NumPy program to implement following operation
to convert a list of numeric values into a one-dimensional NumPy array
Input
import numpy as np
l=[1,2,3,4,5]
print("Original List :" , l)
arr1=np.array(l)
print("One Dimesional Array : ",arr1)
Output
Practical No – 2.2
Aim - Write a NumPy program to implement following operation
to create a 3x3 matrix with values ranging from 2 to 10.
Input
import numpy as np
x = np.arange(2, 11).reshape(3,
3) print(x)
Output
Practical No – 2.3
Aim - Write a NumPy program to implement following operation
to append values at the end of an array.
Input
import numpy as np
x = [10, 20, 30]
print("Original array:")
print(x)
x = np.append(x, [[40, 50], [ 80, 90]])
print("After append values to the end of the array:")
print(x)
Output
Practical No – 2.3
Aim - Write a NumPy program to implement following operation
to create another shape from an array without changing its data(3*2 to 2*3)
Input
import numpy as np
l=[[1,2,3],[4,5,6]]
print("3 * 2 shape of array : \n" , np.reshape(l, (3,2)))
print("2 * 3 shape of previous array : \n" , np.reshape(l, (2,3)))
Output
Practical No – 3.1
Aim - Write a NumPy program to implement following operation
to split an array of 14 elements into 3 arrays, each with 2, 4, and 8
elements in the original order
Input
import numpy as np
l=np.arange(1,15)
print("original array : \n",l)
print("After splitting : \n",np.split(l, [2, 6]))
Output
Practical No – 3.1
Aim - Write a NumPy program to implement following operation
to stack arrays horizontally (column wise)
Input
import numpy as np
x=[1,2,3]
y=[4,5,6]
print("Array-1 : ", np.array(x))
print("Array-2 : ", np.array(y))
print("After horizontally : ", np.hstack((x,y)))
Output
Practical No – 4.1
Aim - Write a NumPy program to implement following operation
to add, subtract, multiply, divide arguments element-wise.
Input
import numpy as np
x=[1,2,3]
y=[4,5,6]
print("addition of two array : ",np.add(x,y))
print("subtract of two array : ",np.subtract(x,y))
print("multiply of two array : ",np.multiply(x,y))
print("divide of two array : ",np.divide(x,y))
Output
Practical No – 4.2
Aim - Write a NumPy program to implement following operation
to round elements of the array to the nearest integer
Input
import numpy as np
l=[1.1,0.4,1.5,1.7]
print("original array : " , l)
x=np.rint(l)
print("Nearest of original array : " , x)
Output
Practical No – 4.3
Aim - Write a NumPy program to implement following operation
to calculate mean across dimension, in a 2D numpy array
Input
import numpy as np
x=np.array([[1,2],[3,4]])
print("Original Array : \n",x)
print("Mean of each column : ",x.mean(axis=0))
print("Mean of each row : ",x.mean(axis=1))
Output
Practical No – 4.4
Aim - Write a NumPy program to implement following operation
to calculate the difference between neighboring elements, elementwise
of a given array
Input
import numpy as np
x=np.array([1,3,7,10,15,19])
print("original list : " , x)
y=np.diff(x)
print("Difference of Original List : ",y)
Output
Practical No – 5.1
Aim - Write a NumPy program to implement following operation
to find the maximum and minimum value of a given flattened array
Input
import numpy as np
arr=np.arange(4).reshape((2,2))
print("original array : \n",arr)
print("Maximum array from flattened array : \n",np.max(arr))
print("Minimum array from flattened array : \n",np.min(arr))
Output
Practical No – 5.2
Aim - Write a NumPy program to implement following operation
to compute the mean, standard deviation, and variance of a given
array along the second axis
Input
import numpy as np
arr=np.arange(6)
print("original array is : ",arr)
print("mean of original array is : ",np.mean(arr))
print("standard deviation of original array is :",np.std(arr))
print("variation of original array is : ",np.var(arr))
Output
Practical No – 6.1
Aim - Write a Pandas program to implement following operation
to convert a NumPy array to a Pandas series
Input
import numpy as
np import pandas
as pd
arr1=np.array([1,2,3,4])
print("Original Array : ",arr1)
arr2=pd.Series(arr1)
print("Pandas Array :
",arr2)
Output
Practical No – 6.1
Aim - Write a Pandas program to implement following operation
to convert the first column of a DataFrame as a Series
Input
import pandas as pd
dit = {'August': [10, 25, 34, 4.85, 71.2, 1.1],
'September': [4.8, 54, 68, 9.25, 58, 0.9],
'October': [78, 5.8, 8.52, 12, 1.6, 11],
'November': [100, 5.8, 50, 8.9, 77, 10]
}
print("original dictionary : \
n",dit) df=pd.DataFrame(dit)
print("After converting into Datadrame : ",df)
Output
Practical No – 6.2
Aim - Write a Pandas program to implement following operation
to create the mean and standard deviation of the data of a given Series
Input
import pandas as pd
data=pd.Series([1,2,3,4,5])
print("original data : ",
data)
print("mean of original data : ", data.mean())
print("standard deviation of original data : ", data.std())
Output
Practical No – 6.3
Aim - Write a Pandas program to implement following operation
to sort a given Series
Input
import pandas as pd
data=pd.Series([21,425,12,67,1])
print("original data : ", data)
print("Sort values of original data : \n",data.sort_values())
Output
Practical No – 7.1
Aim – Write a Pandas program to implement following operation
to create a dataframe from a dictionary and display it
Input
import pandas as
pd data= {
"name" :
['atif','rayhan','hanif','taiyab'],
"age" : [19,20,21,20],
"city" : ['Surat','Bharuch','Surat','Navsari']
}
print("Original DataFrame : \n",pd.DataFrame(data))
Output
Practical No – 7.2
Aim – Write a Pandas program to implement following operation
to sort the DataFrame first by 'name' in ascending order
Input
import pandas as pd
data = {'name': ['Atif', 'Bob', 'Charlie',
'David'], 'age': [25, 30, 28, 32],
'city': ['New York', 'Los Angeles', 'Chicago', 'Houston']}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
Output
Practical No – 7.3
Aim – Write a Pandas program to implement following operation
to delete the one specific column from the DataFrame
Input
import pandas as pd
data = {'name': ['Atif', 'Bob', 'Charlie', 'David'],
'age': [25, 30, 28, 32],
'city': ['New York', 'Los Angeles', 'Chicago', 'Houston']}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
df_sorted = df.sort_values(by='name', ascending=True) print("\
nSorted DataFrame:")
print(df_sorted)
df_modified = df.drop(columns='age') print("\
nDataFrame after deleting 'age' column:")
print(df_modified)
Output
Practical No – 7.4
Aim – Write a Pandas program to implement following operation
to write a DataFrame to CSV file using tab separator
Input
import pandas as pd
data = {'name': ['Atif', 'Bob', 'Charlie', 'David'],
'age': [25, 30, 28, 32],
'city': ['New York', 'Los Angeles', 'Chicago',
'Houston']} df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
df_sorted = df.sort_values(by='name', ascending=True)
print("\nSorted DataFrame:")
print(df_sorted)
df_modified = df.drop(columns='age') print("\
nDataFrame after deleting 'age' column:")
print(df_modified)
# Write the DataFrame to a CSV file with tab separator
df_modified.to_csv('output.csv', sep='\t', index=False)
Output
Practical No – 8
Aim – Write a Pandas program to create a line plot of the opening, closing
stock prices of given company between two specific dates.
Input
import pandas as pd
import matplotlib.pyplot as plt
data = {
'Date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04'],
'Open': [100, 102, 99, 105],
'Close': [98, 101, 100, 103]
}
df = pd.DataFrame(data)
df['Date'] = pd.to_datetime(df['Date'])
plt.figure(figsize=(10, 6))
plt.plot(filtered_data['Date'], filtered_data['Open'], label='Open')
plt.plot(filtered_data['Date'], filtered_data['Close'],
label='Close') plt.title(f'Stock Price Analysis for
{company_name}') plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Output
Practical No – 9
Aim – Write a Pandas program to create a plot of Open, High, Low, Close,
Adjusted Closing prices and Volume of given company between two specific
dates.
Input
import pandas as pd
import matplotlib.pyplot as plt
# Sample CSV data (replace with your actual
data) data = {
'Date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04'],
'Open': [100, 102, 99, 105],
'High': [103, 105, 102, 107],
'Low': [98, 100, 97, 101],
'Close': [98, 101, 100, 103],
'Adj Close': [98, 101, 100, 103],
'Volume': [10000, 12000, 8000, 15000]}
df = pd.DataFrame(data)
# Convert the 'Date' column to datetime format
df['Date'] = pd.to_datetime(df['Date'])
# Specify the company name and date range
company_name = 'Apple Company' # Replace with your desired company
start_date = '2023-01-01'
end_date = '2023-01-04'
# Filter data for the specified date range (removed company filter)
filtered_data = df[(df['Date'] >= start_date) & (df['Date'] <=
end_date)] # Create subplots for each price and volume
# Increased number of columns to match the number of items we want to plot
fig, axs = plt.subplots(nrows=2, ncols=5, figsize=(15, 8))
# Plot Open, High, Low, Close, Adjusted Close
columns = ['Open', 'High', 'Low', 'Close', 'Adj Close']
for i, col in enumerate(columns):
axs[0, i].plot(filtered_data['Date'],
filtered_data[col]) axs[0, i].set_title(col)
axs[0, i].set_xlabel('Date')
axs[0, i].set_ylabel('Price')
# Plot Volume
axs[1, 0].bar(filtered_data['Date'],
filtered_data['Volume']) axs[1, 0].set_title('Volume')
axs[1, 0].set_xlabel('Date')
axs[1,
0].set_ylabel('Volume')
plt.tight_layout()
plt.show()
Output
Practical No – 10.1
Aim – Write a Pandas program to implement following operation
to find and drop the missing values from the given dataset
Input
import pandas as pd
Output
Practical No – 10.2
Aim – Write a Pandas program to implement following operation
to remove the duplicates from the given dataset
Input
import pandas as pd
print(df_cleaned)
# Remove duplicates
df_cleaned = df_cleaned.drop_duplicates()
Output
Practical No – 11
Aim - Write a Pandas program to filter all columns where all entries present,
check which rows and columns has a NaN and finally drop rows with any
NaNs from the given dataset.
Input
import pandas as pd
Output
Practical No – 12
Aim - Write a Python program using Scikit-learn to print the keys, number
of rows-columns, feature names and the description of the given data.
Input
Output
Practical No – 13
Aim - Write a Python program to implement K-Nearest Neighbour supervised
machine learning algorithm for given dataset
Input
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import
train_test_split from sklearn.metrics import
accuracy_score
Output