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

AI Practical File: DataFrame Examples

Uploaded by

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

AI Practical File: DataFrame Examples

Uploaded by

pptwork94
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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=[Link]([90,100,110,120])
array2=[Link]([50,60,70])
array3=[Link]([10,20,30,40])
marksDF = [Link] ([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 = [Link] (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': [Link]([90, 91, 97],index=['Maths','Science','Hindi']),
'Amrita': [Link]([92, 81, 96],index=['Maths','Science','Hindi']),
'Meenakshi': [Link]([89, 91, 88],index=['Maths','Science','Hindi']),
'Rose': [Link]([81, 71, 67],index=['Maths','Science','Hindi']),
'Karthika': [Link]([94, 95, 99],index=['Maths','Science','Hindi'])}
Result = [Link](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': [Link]([90,91,97],
index=['Maths','Science','Hindi']),
'Amrita': [Link]([92, 81, 96],index=['Maths','Science','Hindi']),
'Meenakshi': [Link]([89, 91, 88],index=['Maths','Science','Hindi']),
'Rose': [Link]([81, 71, 67],index=['Maths','Science','Hindi']),
'Karthika': [Link]([94, 95, 99],index=['Maths','Science','Hindi'])}
Result = [Link](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
[Link]['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
[Link]['Science'] = [92, 84, 90, 72, 96, 88]
print(Result)
d) To delete the row containing the marks of Hindi.
Result = [Link]('Hindi', axis=0) #delete the row “Hindi”
print(Result)
e) To delete the columns having heading as Rajat, Meenakshi & Karthika.
#delete multiple columns
Result = [Link](['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": [Link](["Arnav","Megha","Priya","Rahul"],
index=["Data 1","Data 2","Data 3","Data 4"]),
"Marks": [Link]([85, 92, 78, 83], index=["Data 1","Data 2","Data
3","Data 4"]),
"Sports": [Link](["Cricket","Volleyball","Hockey","Badminton"],
index=["Data 1","Data 2","Data 3","Data 4"])}
# creating a DataFrame
df = [Link](dict)
# printing this DataFrame on the output screen
print(df)

b) To diplay the index of the DataFrame.


print([Link])
c) To display columns heading of the DataFrame.
print([Link])
d) To display total no. of rows and columns in the DataFrame.
print([Link])
e) To display the top two rows of the DataFrame.
print([Link](2))
f) To display the last two rows of the DataFrame.
print([Link](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([Link]())
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([Link]().sum())
d) To delete the rows containing missing values.
print([Link]())
e) To replace all the missing values with a Zero.
print([Link](0))

9. WAP to convert Celsius to Fahrenheit using Tensorflow Library.


#Importing Libraries
import tensorflow as tf
import numpy as np
import [Link] as plt
#Training Data
c = [Link]([-40, -10, 0, 8, 15, 22, 38], dtype=float)
f = [Link]([-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 = [Link]([[Link](units=1,input_shape=[1])])
#Compile, loss, optimizer
[Link] (loss='mean_squared_error',
optimizer=[Link](0.1),
metrics=['mean_squared_error'])
#Train the model
history = [Link](c, f, epochs=500, verbose=False)
print("Finished training the model")
#Training Statistics
[Link]('Epoch Number')
[Link]("Loss Magnitude")
[Link]([Link]['loss'])
[Link]()
#Predict Values
print([Link]([Link]([100.0])))

Common questions

Powered by AI

Using TensorFlow for conversion involves creating a neural network model. Start by initializing input (Celsius) and output (Fahrenheit) arrays. A simple model structure involves a single `Dense` layer with one neuron, reflecting a direct mapping computation. Compiling the model with appropriate loss function (mean squared error) and optimizer (Adam optimizer) prepares the network. Training involves fitting the model against the data for several epochs. This use of neural networks is more demonstrative of TensorFlow’s ability to solve linear transformation problems than practical, as a simple mathematical formula would suffice in real conversion tasks .

To add a new column to an existing DataFrame, you can directly assign a list of values to a new column name, such as `Result['NewColumn'] = [values]`. Index alignment is crucial, as the length of the list must match the DataFrame's index length; otherwise, a ValueError will be raised. Aligning indices ensures data integrity across columns .

Verify a DataFrame's structure using attributes like `df.shape` to get row and column counts, `df.index` for indices, and `df.columns` for column names. For summary statistics, `df.describe()` provides metrics like mean, standard deviation, and percentiles. These insights reveal data distribution, identify abnormalities, and highlight potential outliers, assisting in informed data cleaning and analysis strategies .

To modify existing values for a specific row, use `loc` with the row label index, e.g., `df.loc['Science'] = [new_values]`. If the data is not aligned correctly with the DataFrame's structure, it can lead to unexpected data corruption, overwriting intended values, or introducing errors, which can propagate downstream in analysis and result in flawed insights .

To check for any missing values in a DataFrame, use `df.isnull()` to generate a DataFrame of boolean values indicating missing data. To check a specific column, you can apply `.isnull().any()` on the column data (e.g., `df['ColumnName'].isnull().any()`). This method identifies where imputation or data cleaning might be needed .

To create a DataFrame from a list of dictionaries in Pandas, you initialize the listDict with dictionaries, then pass it to pd.DataFrame(). Each dictionary represents a row, and keys of the dictionaries act as column names. Missing values may arise if some dictionaries do not contain all possible keys, resulting in NaNs for those cells .

To drop multiple columns, use `drop()` with the column names in a list and specify `axis=1`, such as `df.drop(['Column1', 'Column2'], axis=1)`. This is necessary when the columns are non-essential or could hinder analysis, such as redundant, irrelevant, or biased data, enabling a cleaner and more focused dataset for reliable conclusions .

To replace missing values with zeros in a DataFrame, use the `fillna()` method with 0 as an argument (e.g., `df.fillna(0)`). Replacing missing values with zeros can ensure uniformity in data size and structure, allowing for smoother analytical operations. However, it may distort data interpretation by introducing bias, especially if zeros have contextual significance in the dataset .

When you create a DataFrame from arrays with varying lengths, Pandas will align elements based on their positions, filling the unmatched positions with NaN. This is evident when using `np.array()` to initialize DataFrames, as seen in the example where array2's third value is missing. This necessitates careful handling for data analysis purposes, as NaN can affect computations and require cleaning or imputation .

Pandas provides a high-level data structure with DataFrames, which makes it easy to manipulate and analyze large datasets with simple operations, offering built-in tools for aligning data, handling missing data, and performing complex statistical operations with ease. Using Pandas with dictionaries and lists, users can harness its indexing, slicing, and various functionalities to simplify data transformation and analysis significantly .

You might also like