Sei sulla pagina 1di 3

Python test:

1. Consider the two below expressions:

a. A = [‘Bangalore’, ‘Pune’. ‘Delhi’, ‘Mumbai’]


b. A = set([‘Bangalore’, ‘Pune’. ‘Delhi’, ‘Mumbai’])

How would you search for ‘Bangalore’ in these? Which structure is more optimal for searching
and why?
1) A = [‘Bangalore’, ‘Pune’, ‘Delhi’, ‘Mumbai’]

# initializing list
A= ['Bangalore', 'Pune', 'Delhi', 'Mumbai']

# initializing substring
substr = 'Bangalore'

# to get string with substring


res = [i for i in A if substr in i]

# printing result
print ("String being searched for : " + str(res))

Output: String being searched for : ['Bangalore']

2)A = set([‘Bangalore’, ‘Pune’, ‘Delhi’, ‘Mumbai’])

# initializing list
A= set(['Bangalore', 'Pune', 'Delhi', 'Mumbai'])

# initializing substring
substr = 'Bangalore'

# to get string with substring


res = [i for i in A if substr in i]

# printing result
print ("String being searched for : " + str(res))

Output: String being searched for : ['Bangalore']


2. Consider a function “fun” as defined below:

Def fun(x):

x[0] = 5

return x

If g= [10,11,12], what will be the output of the statement: print fun(g), g

Output will be: [5,11,12][5,11,12]

3. While importing a file “temp.csv” using pandas, you encounter the following error:

Traceback (most recent call last):

File "<input>", line 1, in<module>

UnicodeEncodeError: 'ascii' codec can't encode character.

What is the cause of this and how would you fix it?

Here the error is related to ASCII code, and if a character string is not there in ASCII code page,
above error will be shown. Possibly the code is not running in Python 3.x version. For fixing
either we need to run the code in Python 3.x version, or use a unicode string at the top of the
code. Here we can use encoding ‘utf-8’.

4. Given a list of strings as shown below, how would you convert them to datetime format?

['01 Jan 2010', '02-02-2011', '20120303', '2013/04/04', '2014-05-05', '2015-06-06T12:20']

These strings can be converted to datetime format, by importing a packaged library named
datetime where we need to define the syntax of date. See below example:

from datetime import datetime


date_str = '20120303'
date_object = datetime.strptime(date_str, '%Y%m%d').date()
print(date_object) # printed in default formatting
Output: 2012-03-03
from datetime import datetime
date_str = '02-02-2011'
date_object = datetime.strptime(date_str, '%d-%m-%Y').date()
print(date_object) # printed in default formatting
Output : 2011-02-02
5. Write a sample code to find and replace missing values in a pandas dataframe with ‘0’.
import pandas as pd
cars = pd.read_csv("cars.csv")
cars[“Mileage”].fillna(0, inplace = True)
cars

6. From the SQL part of the test, pick out any two questions and solve them in python using
pandas.

Potrebbero piacerti anche