Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

IC208 - Programming for Finance

Seminar 4 – Solutions

Q1) Pandas key data structure is called?

A. Keyframe

B. DataFrame

C. Statistics

D. Econometrics

Ans: B

Pandas is built on the Numpy package and its key data structure is called the DataFrame.

Q2) Which of the following statement can be applied to a DataFrame?

A. Potentially columns are of different types

B. Can Perform Arithmetic operations on rows and columns

C. Labeled axes (rows and columns)

D. All of the above

Ans: D

Q3) What will be output for the following code?

import pandas as pd

import numpy as np

df = pd.DataFrame(np.random.rand(10))

print(df.shape[1])

A. 10

B. error message

C. (10,1)

D. 1


Ans: D

np.random.rand(10)                                  #create a Numpy (10,1) array

pd.DataFrame(np.random.rand(10))             #create a DataFrame 10 rows x 1 col

df.shape                                                    #create tuple (10,1)

df.shape[1]                                               #assess to 2nd element of the tuple


Q4) Write codes to create 02 dataframes of random numbers between 0 and 100. Dataframe 1 has 10 rows x 1 column. The column is named num1’ while dataframe 2 has 5 rows x 2 columns. The columns are named ‘num2’,’num3’ .

Ans:

rand_nums = np.random.rand(10) * np.random.randint(0,100) df1 = pd.DataFrame(rand_nums, columns=['num1'])

rand_nums = np.random.rand(5,2) * np.random.randint(0,100) df2 = pd.DataFrame(rand_nums, columns=['num2','num3'])

Q5) Write codes to add a column, named ‘firm_id’ in both ofthe above dataframes. The column ‘firm_id’ in the first dataframe takes random integer values from  1 to  10 while column ‘firm_id’ in the second dataframe takes random integer values from 1 to 5.

Ans:

rand_integers = np.random.randint(1,10,10)

df1['firm_id'] = pd.DataFrame(rand_integers)

rand_integers = np.random.randint(1,5,5)

df2['firm_id'] = pd.DataFrame(rand_integers)

Q6) Write codes to create a new dataframe which include all observations/rows from both of the dataframes in Q5.

Ans:

df3 = pd.concat((df1,df2))

or

df3 = df1.append(df2)

Q7) Write codes to create a new dataframe which combine both of the dataframes in Q5 based on column firm_id’ .

Ans:

df3 = df1.merge(df2,on='firm_id')

df3 = df1.merge(df2,on='firm_id', how='outer')

df3 = df1.merge(df2,on='firm_id', how='left') 

Q8) Write short codes for a (random) passwords generator.

Ans:

There are different ways. Below is an example.

import random

def passw_gen(length):

c = []

for i in range(length):

c.append(chr(random.randint(33,126)))

return "".join(c)

l = random.randint(10,25)

#print(passw_gen(l))

Q9) Define a class named ICMA_student’ with 03 attributes and 03 methods, which can be applied on the class ‘ICMA_student’ . Create an object of the class and apply the methods on the object.

Ans: There are different ways. Below is an example.