Artificial Intelligence Practical File
1. WAP to create a Series from Scalar Values.
import pandas as pd #import Pandas with alias pd
series1 = pd. Series ([10,20,30]) #create a Series
print(series1) #Display the series
Output –
0 10
1 20
2 30
dtype: int64
2. WAP to create a DataFrame from NumPy arrays.
array1=np.array([90,100,110,120])
array2=np.array([50,60,70])
array3=np.array([10,20,30,40])
marksDF = pd.DataFrame ([array1, array2, array3], columns=[ 'A', 'B', 'C', 'D'])
print(marksDF)
Output –
A B C D
0 90 100 110 120.0
1 50 60 70 NaN
2 10 20 30 40.0
3. WAP to create a DataFrame from dictionary of array/lists:
import pandas as pd # initialize data of lists.
data = {'Name': ['Varun', 'Ganesh', 'Joseph', 'Abdul', 'Reena'],
'Age': [37,30,38,39,40]}
# Create DataFrame
df = pd.DataFrame (data)
# Print the output.
print(df)
Output –
Name Age
0 Varun 37
1 Ganesh 30
2 Joseph 38
3 Abdul 39
4 Reena 40
4. WAP to create a DataFrame from List of Dictionaries.
# Create list of dictionaries
listDict = [{'a':10, 'b':20}, {'a': 5, 'b':10, 'c':20}]
a= pd. DataFrame (listDict)
print(a)
Output –
a b c
0 10 20 Nan
1 5 10 20.0
5. WAP to create a DataFrame on the given data using dictionary.
Rajat Amrita Meenakshi Rose Karthika
Maths 90 92 81 81 94
Science 91 81 71 71 95
Hindi 97 96 67 67 99
import pandas as pd
ResultSheet={'Rajat': pd.Series([90, 91, 97],index=['Maths','Science','Hindi']),
'Amrita': pd.Series([92, 81, 96],index=['Maths','Science','Hindi']),
'Meenakshi': pd.Series([89, 91, 88],index=['Maths','Science','Hindi']),
'Rose': pd.Series([81, 71, 67],index=['Maths','Science','Hindi']),
'Karthika': pd.Series([94, 95, 99],index=['Maths','Science','Hindi'])}
Result = pd.DataFrame(ResultSheet)
print(Result)
6. WAP for the following conditions based on the given data:
Rajat Amrita Meenakshi Rose Karthika
Maths 90 92 81 81 94
Science 91 81 71 71 95
Hindi 97 96 67 67 99
a) To add a new column for another student ‘Fathima’ = 89, 78, 76
import pandas as pd
ResultSheet={'Rajat': pd.Series([90,91,97],
index=['Maths','Science','Hindi']),
'Amrita': pd.Series([92, 81, 96],index=['Maths','Science','Hindi']),
'Meenakshi': pd.Series([89, 91, 88],index=['Maths','Science','Hindi']),
'Rose': pd.Series([81, 71, 67],index=['Maths','Science','Hindi']),
'Karthika': pd.Series([94, 95, 99],index=['Maths','Science','Hindi'])}
Result = pd.DataFrame(ResultSheet)
print(Result)
Result['Fathima']=[89,78,76]
print(Result)
b) To add a new row to a DataFrame: English = 90, 92, 89, 80, 90, 88
Result.loc['English'] = [90, 92, 89, 80, 90, 88]
print(Result)
c) To change the values for Science and replace them with the new ones.
Science = 92, 84, 90, 72, 96, 88
Result.loc['Science'] = [92, 84, 90, 72, 96, 88]
print(Result)
d) To delete the row containing the marks of Hindi.
Result = Result.drop('Hindi', axis=0) #delete the row “Hindi”
print(Result)
e) To delete the columns having heading as Rajat, Meenakshi & Karthika.
#delete multiple columns
Result = Result.drop(['Rajat','Meenakshi','Karthika'], axis=1)
print(Result)
7. WAP for the following:
a) To create a DataFrame on the data given below.
Student Marks Sports
Data 1 Arnav 85 Cricket
Data 2 Megha 92 Volleyball
Data 3 Priya 78 Hockey
Data 4 Rahul 83 Badminton
import pandas as pd
# creating a 2D dictionary
dict = {"Student": pd.Series(["Arnav","Megha","Priya","Rahul"],
index=["Data 1","Data 2","Data 3","Data 4"]),
"Marks": pd.Series([85, 92, 78, 83], index=["Data 1","Data 2","Data
3","Data 4"]),
"Sports": pd.Series(["Cricket","Volleyball","Hockey","Badminton"],
index=["Data 1","Data 2","Data 3","Data 4"])}
# creating a DataFrame
df = pd.DataFrame(dict)
# printing this DataFrame on the output screen
print(df)
b) To diplay the index of the DataFrame.
print(df.index)
c) To display columns heading of the DataFrame.
print(df.columns)
d) To display total no. of rows and columns in the DataFrame.
print(df.shape)
e) To display the top two rows of the DataFrame.
print(df.head(2))
f) To display the last two rows of the DataFrame.
print(df.tail(2))
8. WAP for the following based on the data given below:
Maths Science English Hindi AI
Heena 90 92.0 89 81.0 94.0
Shefali 91 81.0 91 71.0 95.0
Meera 97 88 67.0 99.0
Joseph 89 87.0 78 82.0
Suhana 65 50.0 77 96.0
Bismeet 93 88.0 82 89.0 99.0
a) To check whether the DataFrame has any missing values or not.
print(marks.isnull())
b) To check missing values in the column with the heading Science.
print(marks['Science'].isnull().any())
c) To find total number of missing values in the given DataFrame.
print(marks.isnull().sum())
d) To delete the rows containing missing values.
print(marks.dropna())
e) To replace all the missing values with a Zero.
print(marks.fillna(0))
9. WAP to convert Celsius to Fahrenheit using Tensorflow Library.
#Importing Libraries
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#Training Data
c = np.array([-40, -10, 0, 8, 15, 22, 38], dtype=float)
f = np.array([-40, 14, 32, 46, 59, 72, 100], dtype=float)
#Creating a model
#Since the problem is straightforward, this network will require only a single
layer, with a single neuron.
model = tf.keras.Sequential([tf.keras.layers.Dense(units=1,input_shape=[1])])
#Compile, loss, optimizer
model.compile (loss='mean_squared_error',
optimizer=tf.keras.optimizers.Adam(0.1),
metrics=['mean_squared_error'])
#Train the model
history = model.fit(c, f, epochs=500, verbose=False)
print("Finished training the model")
#Training Statistics
plt.xlabel('Epoch Number')
plt.ylabel("Loss Magnitude")
plt.plot(history.history['loss'])
plt.show()
#Predict Values
print(model.predict(np.array([100.0])))