Module 4: Working with Data in Python

Looking for ‘python for data science ai & development module 4 answers‘?

In this post, I provide accurate answers and detailed explanations for Module 4: Working with Data in Python of Course 4: Python for Data Science, AI & Development IBM Generative AI Engineering Professional Certificate

Whether you’re preparing for quizzes or brushing up on your knowledge, these insights will help you master the concepts effectively. Let’s dive into the correct answers and detailed explanations for each question.

Practice Quiz: Reading and Writing Files with Open

Practice Assignment

1. What are the most common modes used when opening a file?

  • (a)ppend, (r)edline, (w)rite
  • (s)ave, (r)ead, (w)rite
  • (a)ppend, (r)ead, (w)rite ✅
  • (a)ppend, (c)lose, (w)rite

Explanation:

  • When working with files in Python, the three primary modes are:
    • (r)ead: Opens the file for reading only.
    • (w)rite: Opens the file for writing (creates a new file or overwrites an existing file).
    • (a)ppend: Opens the file for appending (writing data to the end of the file without overwriting existing content).
  • Other options like (s)ave, (r)edline, or (c)lose are not valid file modes in Python.

2. What is the data attribute that will return the title of the file?

  • File1.open()
  • File1.mode
  • File1.name ✅
  • File1.close()

Explanation:
The .name attribute in Python returns the name of the file as a string.

3. What is the command that tells Python to begin a new line?

  • \n ✅
  • \q
  • \b
  • \e

Explanation:
The \n escape sequence is used to represent a newline in Python.

4. What attribute is used to input data into a file?

  • File1.close()
  • File1.open()
  • File1.write() ✅
  • File1.read()

Explanation:
The .write() method is used to write data to a file in Python.

Practice Quiz: Pandas

Practice Assignment

5. What python object do you cast to a dataframe?

  • Set
  • Tuple
  • Dictionary ✅
  • Lists

Explanation:
A dictionary is often cast to a DataFrame in Python. Each key in the dictionary becomes a column, and the corresponding values are the data for those columns.

6. How would you access the first-row and first column in the dataframe df?

  • df.ix[0,0] ✅
  • df.ix[0,1]
  • df.ix[1,0]
  • df.ix[1,1]

Explanation:

  • The .iloc method in pandas is used for positional indexing (row and column numbers).
  • df.iloc[0, 0] retrieves the value at the first row (index 0) and first column (index 0).

7. What is the proper way to load a CSV file using pandas?

  • pandas.from_csv(‘data.csv’)
  • pandas.load_csv(‘data.csv’)
  • pandas.read_csv(‘data.csv’) ✅
  • pandas.import_csv(‘data.csv’)

Explanation:

  • The correct function to load a CSV file is pandas.read_csv().
  • Example:
    import pandas as pd
    df = pd.read_csv(“data.csv”)

8. Use this dataframe to answer the question.

How would you select the Genre disco? Select all that apply.

  • df.iloc[6, ‘genre’]
  • df.loc[6, 5]
  • df.iloc[6, 4] ✅
  • df.loc[‘Bee Gees’, ‘Genre’]

Explanation:

  • The .iloc method uses zero-based indexing to access data by row and column positions.
  • 6 corresponds to the 7th row (indexing starts at 0), and 4 corresponds to the 5th column.
  • Example:
    genre = df.iloc[6, 4]
    print(genre) # Outputs: Disco

9. Assume that you have a data frame containing details of various musical artists, their famous albums, their genres, and various other parameters. Here, `Album` is the second column. How do we retrieve records from row 3 through row 6?

  • df.loc[2:5, 1]
  • df.loc[2:5, ‘Album’] ✅
  • df.iloc[2:6, 3]
  • df.loc[2, ‘Album’]

Explanation:

  • The .loc method is label-based indexing, and slicing rows in pandas includes the end of the range.
  • 2:5 retrieves rows 3 through 6 (inclusive), and 'Album' specifies the second column.
  • Example:
    album_records = df.loc[2:5, “Album”]
    print(album_records)

10. Use this dataframe to answer the question.

Which will NOT evaluate to 20.6? Select all that apply.

  • df.iloc[4,5]
  • df.iloc[6,5]
  • df.loc[4,’Music Recording Sales’] ✅
  • df.iloc[6, ‘Music Recording Sales (millions)’] ✅

11. Use this dataframe to answer the question.

How do we select Albums The Dark Side of the Moon to Their Greatest Hits (1971-1975)? Select all that apply.

  • df.iloc[2:5, ‘Album’]
  • df.loc[2:5, ‘Album’] ✅
  • df.iloc[2:6, 1] ✅
  • df.loc[2:5, 1]

Practice Quiz: Numpy in Python

Practice Assignment

12. What is the Python library used for scientific computing and is a basis for Pandas?

  • Requests
  • Tkinter
  • Numpy ✅
  • datetime

Explanation:

  • NumPy (Numerical Python) is a core library used in scientific computing, providing support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays.
  • Pandas relies heavily on NumPy for its data structures and numerical operations.
  • Other options like Requests, OS, and datetime are unrelated to scientific computing.

13. What attribute is used to retrieve the number of elements in an array?

  • a.size ✅
  • a.ndim
  • a.shape
  • a.dtype

Explanation:

  • The .size attribute in NumPy returns the total number of elements in the array.
  • Example:
    import numpy as np
    a = np.array([[1, 2], [3, 4]])
    print(a.size) # Outputs: 4

14. How would you change the first element to "10" in this array c:array([100,1,2,3,0])?

  • c[0]=10 ✅
  • c[4]=10
  • c[2]=10
  • c[1]=10

Explanation:

  • In NumPy, array elements are accessed using zero-based indexing. c[0] refers to the first element of the array. To modify it, simply assign a new value.
  • Example:
    import numpy as np
    c = np.array([100, 1, 2, 3, 0])
    c[0] = 10
    print(c) # Outputs: [10, 1, 2, 3, 0]

15. What attribute is used to return the number of dimensions in an array?

  • a.ndim ✅
  • a.shape
  • a.size
  • a.dtype

Module 4 Graded Quiz: Working with Data in Python

Graded Assignment

16. What is the result of the following lines of code?

a=np.array([-1,1])
b=np.array([1,1])
np.dot(a,b)

  • array([0,2])
  • 1
  • 0 ✅
  • array([[-1, -1], [1, 1]])

Explanation:
The dot product is calculated as: (−1×1)+(1×1)=−1+1=0(-1 \times 1) + (1 \times 1) = -1 + 1 = 0

17. How do you perform matrix multiplication on the numpy arrays A and B ?

  • A+B
  • A*B
  • np.dot(A,B) ✅
  • A – B

Explanation:
np.dot performs matrix multiplication in NumPy.

18. What values does the variable out take if the following lines of code are run?

X=np.array([[1,0,1],[2,2,2]])
out=X[0:2,2]
out

  • array([1,0])
  • array([1,2]) ✅
  • array([1,1])
  • array([0,2])

Explanation:
Slicing selects the elements in column 2 (index 2) from both rows.

19. What is the value of Z after the following code is run?

X=np.array([[1,0],[0,1]])
Y=np.array([[2,1],[1,2]])
Z=np.dot(X,Y)

  • array([[2,1],[1,2] ]) ✅
  • array([[2,0],[1,0]])
  • array([[3,1],[1,3] ])
  • array([[1,0],[0,1]])

Explanation:
Matrix multiplication results in the same values as matrix Y since X is the identity matrix.

20. Consider the following text file: Example1.txt:

This is line 1

This is line 2

This is line 3

What is the output of the following lines of code?

with open("Example1.txt","r") as File1:

file_stuff=File1.readline ()

print(file_stuff)

  • This is line 1
  • This is line 1
    This is line 2
    This is line 3 ✅

  • This is line 1

    This is line 2

Explanation:
The read method reads the entire content of the file.

21. Consider the following line of code:

with open(example1,"r") as file1:

What mode is the file object in?

  • read ✅
  • write
  • append
  • binary

Explanation:
The mode 'r' specifies the file is opened for reading.

22. What do the following lines of code do?

with open("Example1.txt","r") as file1:

FileContent=file1.readlines()

print(FileContent)

  • Read the file “Example1.txt” ✅
  • Write to the file “Example1.txt”
  • Append the file “Example1.txt”

23. What do the following lines of code do?

with open("Example.txt","a") as writefile:

writefile.write("This is line A\n")
writefile.write("This is line B\n")

  • Write to the file “Example.txt” ✅
  • Read the file “Example.txt”
  • Append the file “Example.txt”
  • Create a binary file “Example.txt”

Explanation:
The mode 'w' overwrites or creates the file for writing.

24. What task do the following lines of code perform?

with open('Example2.txt','r') as readfile:
with open('Example3.txt','w') as writefile:
for line in readfile:
writefile.write(line)

  • Copy the text from Example2.txt to Example3.txt. ✅
  • Print out the content of Example2.txt.
  • Check the mode of the open function for each file object.

25. Consider the dataframe df. How would you access the element in the 2nd row and 1st column?

  • df.iloc[1,0] ✅
  • df.iloc[2,1]
  • df.iloc[0,1]

26. In the lab, you learned you can also obtain a series from a dataframe df, select the correct way to assign the column with the header Length to a pandas series to the variable x.

  • x=df[‘Length’] ✅
  • x=df[[‘Length’]]
  • x=df.[[‘Length’]]

27. Given the dataframe df, how can you retrieve the element in the first row and first column?

  • df.iloc[0,0] ✅
  • df.iloc[2,1]
  • df.iloc[0,1]
  • df.iloc[1,2]

Explanation:
.iloc accesses rows and columns by index, starting from 0.

28. What function would you use to load a CSV file in Pandas?

  • pd.load_csv(path)
  • np.read_csv(path)
  • pd.read_csv(path) ✅
  • pd.read_excel(path)

Explanation:
The read_csv function is used to load CSV files into a Pandas DataFrame.

Related contents:

You might also like:

Leave a Reply