python lab solutions (1)
python lab solutions (1)
Now, try to run python on the command prompt. Type the command python -version in case of
python3.
b)Declaring variables
AIM: To implement variable declaration
a = 20
b = 10.5
c = "Hello"
d = False
e = 5 + 3j
print(str(a))
print(float(a))
print(bool(a))
print(complex(a))
print(str(b))
print(int(b))
print(bool(b))
print(complex(b))
print(str(e))
print(bool(e))
OUTPUT:
d) Type of a variable
a = 20
b = 10.5
c = "Hello"
d = False
e = 5 + 3j
f = [1,2,3,4,5]
g = {1:"a",2:"b",3:"c"}
h = (1,2,3,4,5)
i = range(10,20)
j = {"abc","efg","uvw","xyz"}
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))
print(type(g))
print(type(h))
print(type(i))
print(type(j))
e) Multiple assignments
#Assign the same value to multiple variables
a = b = c = 30
p = q = r = [100,200,300]
#Assign multiple values to multiple variables
x, y, z = 10, 15, 20
u, v, w = 0.453, "hey", True
print(a)
print(b)
print(c)
print(p)
print(q)
print(r)
print(x)
print(y)
print(z)
print(u)
print(v)
print(w)
OUTPUT:
OUTPUT:
OUTPUT:
i) Arithmetic operators
x = 15
y=4
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)
OUTPUT:
OUTPUT:
OUTPUT:
iv) Bitwise operators
a = 10
b=4
print("a & b =", a & b)
print("a | b =", a | b)
print("~a =", ~a)
print("a ^ b =", a ^ b)
# shift operators
a = 10
b = -10
print("a >> 1 =", a >> 1)
print("b >> 1 =", b >> 1)
a=5
b = -10
print("a << 1 =", a << 1)
print("b << 1 =", b << 1)
OUTPUT:
v) Assignment operators
a = 21
b = 10
c=0
c=a+b
print("Initial value=",c)
c += a
print("c+a=",c)
c -= a
print("c-a=",c)
c *= a
print("c*a=",c)
c /= a
print("c/a=",c)
c =2
c %= a
print("c%a=",c)
c **= a
print("c**a=",c)
c //= a
print("c//a=",c)
OUTPUT:
OUTPUT:
False
True
False
OUTPUT:
True
True
True
False
EXPERIMENT-2
OUTPUT:
If-else statement:
Syntax:
if condition:
#block of statements
else:
#another block of statements (else-block)
Program:
Program to check if a number is even or odd using if-else statement.
if num%2 == 0:
print("Number is even...")
else:
print("Number is odd...")
OUTPUT:
If-elif statement:
if expression 1:
# block of statements
elif expression 2:
# block of statements
else:
# block of statements
Program:
marks = int(input("Enter the marks? "))
if marks > 85 and marks <= 100:
print("You scored grade A ...")
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
print("You scored grade C ...")
else:
print("Sorry you failed")
OUTPUT:
b)Implement python program on and conditional branching statements:
AIM: To Implement python program on and conditional branching statements:
1. If-statement:
Syntax:
if test-expression==True:
statement(s)
Program:
a=int(input(“enter a”))
b=int(input(“enter b”))
if a > b:
print("a is greater than b")
OUTPUT:
If-else statement:
Syntax:
if condition:
#block of statements
else:
#another block of statements (else-block)
Program:
x=int(input("enter a value"))
if x > 0:
print("It's a positive number")
else:
print("It's not a positive number")
OUTPUT:
If-elif statement:
if expression 1:
# block of statements
elif expression 2:
# block of statements
else:
# block of statements
Program:
x=int(input("enter value of x"))
if x < 0:
print("x is a negative")
elif x == 0:
print("x is 0")
else:
print("x is positive")
OUTPUT:
Experiment-3
Python programs on looping control structures
a) Design and develop programs using Iterative statements- while, for, nested
loops
AIM: To design and develop programs using Iterative statements- while, for, nested
loops
PROGRAM:
while looP
count = 0
count = count + 1
print("Hello CSE")
OUTPUT:
for loop
n=4
print(i)
OUTPUT:
Nested loops
for i in range(1, 11):
# nested loop
print()
PROGRAM:
for i in range(1,11):
if i == 2**3:
break
print(i)
OUTPUT:
Continue statement
for i in range(1,21):
if i%2 == 0:
continue
print(i)
OUTPUT:
Pass statement
s = "python"
for i in s:
pass
for i in s:
if i == 'o':
print('Pass executed')
pass
print(i)
OUTPUT:
AIM: To understand the usage of else statement in loops with a case study
PROGRAM:
count=1
while(count<6):
print(count)
count+=1
else:
OUTPUT:
EXPERIMENT-4
Identify the need and importance in the creation of python Functions and modules
Syntax:
def function_name():
statements
function call:
function_name()
Program:
Function to find number is even or odd:
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)
OUTPUT:
Program:
def func():
l="local variable" #local scope
print(l)
print(s+" inside function ")
s="global variable" #global scope
func()
print(s+ " outside function")
OUTPUT:
Program:
def f():
global s
s += "world"
print(s)
s = "Changed the global variable"
print(s)
# Global Scope
s = "Hello"
f()
print(s)
OUTPUT:
Fruitful functions:
The functions with a return value.
Void functions:
The functions which donot have a return value.
OUTPUT:
OUTPUT:
RECURSIVE:
It is a process in which a function calls itself directly or indirectly.
Program(recursive):
def recursive_fact(n):
if n == 1:
return n
else:
return n * recursive_fact(n-1)
# user input
num = int(input("enter a number"))
print(“factorial”+str(recursive_fact(num)))
OUTPUT:
LAMBDA:
Python Lambda Functions are anonymous function means that the function is
without a name.
lambda arguments: expression
Program(lambda):
Python program to find cube of a number using lambda function:
n=int(input("enter a number"))
print(cube(n))
OUTPUT:
Enter a number : 3
27
1. Keyword arguments:
The idea is to allow the caller to specify the argument name with values so
that caller does not need to remember the order of parameters .
Program:
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname="Hello", lastname='World')
student(lastname='World', firstname='Hello')
OUTPUT:
Hello World
Hello World
2. Default arguments:
A default argument is a parameter that assumes a default value if a value is
not provided in the function call for that argument.
Program:
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
myFun(10)
OUTPUT:
x: 10
y: 50
Program:
def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', 'Python')
OUTPUT:
Install Modules:
You can install modules or packages with the Python package manager (pip). To install a module
system wide, open a terminal and use the pip command. If you type the code below it will
install the module.
sudo pip install module-name
In order for this to work, you need to have pip installed. The installation process depends on
your platform.
python –version
Math(module):
The math module is a collection of mathematical functions.
Program:
import math
print(math.pi)
print(math.ceil(3.3))
print(math.floor(3.3))
print(math.sqrt(10))
OUTPUT:
Random module:
Program:
import random
print(random.random())
pets = ["cat", "dog", "fish"]
print(random.choice(pets))
print(random.randint(1, 10))
OUTPUT:
g) Python Packages:
A package is a hierarchical file directory structure that has modules and other packages within
it. Every package in Python is a directory which must have a special file called __init__.py. It is
simply added to indicate that this directory is an ordinary directory and contains a Python
package .You can import a package as the same way as a module.
To create a package called MyPackage ,create a directory called MyPackage having the module
MyModule and the __init__.py file. Now to use MyModule in program you must first import it.
Import MyPackage.MyModule
Or
Solve the problems using Strings and understanding the methods and operations on Lists.
Program:
x = 'dance'
print("Geeta could both %s and %s. "%('sing',x))
Program:
String methods:
txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple")
print(x)
k=txt.capitalize()
print(k)
p=txt.find(“apples”)
print(p)
l = txt.islower()
print(l)
r = txt.replace("apples", "oranges")
print(r)
h = txt.split()
print(h)
str= "CompanyX"
n= str.isalpha()
print(n)
str1=”35667”
print(str1.isnumeric())
str2=”THIS IS IT!”
print(str2.isupper())
str3=” hi I am PETER”
print(str3.swapcase())
OUTPUT:
REGULAR EXPRESSIONS:
import re
string = """Hello my Number is 123456789 and
my friend's number is 987654321"""
regex = '\d+'
match = re.findall(regex, string)
print(match)
print(re.split('\W+', 'Words, words , Words'))
print(re.split('\d+', 'On 12th Jan 2016, at 11:02 AM'))
regex1 = r"([a-zA-Z]+) (\d+)"
s = "Welcome to Python"
res = re.search(r"\bP", s)
print(res.start())
print(res.end())
print(res.span())
OUTPUT:
EXPERIMENT-6
Programs on the implementation of methods and operations of List data Structure.
a)Define a list and write a programs to access and modify element of a list.
AIM: To define a list and write program to access and modify the elements in it.
Program:
1) Creating a list:
l1 = [1, 2, 3]
l2 = []
l3 = [1, "Hello", 3.4]
l4= ["mouse", [8, 4, 6], ['a']]
print(l1)
print(l2)
print(l3)
print(l4)
OUTPUT:
2) Accessing a list:
my_list = ['h', 'e', 'l', 'l', 'o']
print(my_list[0])
print(my_list[2])
for i in my_list:
print(i)
n_list = ["Hello", [2, 0, 1, 5]]
print(n_list[0][1])
print(n_list[1][3])
OUTPUT:
3) Modifying list elements:
nums= [2, 4, 6, 8]
nums[0] = 1
print(nums)
nums[1:4] = [3, 5, 7]
print(nums)
nums.append(7)
print(nums)
print(nums+ [9, 7, 5])
nums.insert(1,10)
print(nums)
OUTPUT:
Operations: 1. Append()
2.extend()
3.insert()
4.remove()
5.pop()
6.slice
7.len()
8.min()or max()
Program:
l= [2, 4, 6, 8]
l.append(7)
l.append(9)
print(l)
l.extend([10,12,14])
print(l)
l.insert(3,20)
print(l)
l.remove(10)
print(l)
l.pop(0)
print(l)
print(l[2:4])
l.reverse()
print(l)
print("length":+str(len(l)))
print("max:" +str(max(l)))
print("min:" +str(min(l)))
OUTPUT:
List methods:
1. Sort()
2. Reverse()
3. Sum()
4. Index()
5. Count()
6. Min() or max()
Program:
l= [5,2, 4, 2, 8]
l.sort()
print("sorted list:")
print(l)
l.reverse()
print("reversed list")
print(l)
print("sum:"+str(sum(l)))
print("len:"+str(len(l)))
print("count:"+str(l.count(2)))
print("index of:"+ str(l.index(2)))
print("max:"+str(max(l)))
print("min:"+str(min(l)))
OUTPUT:
stack = [1, 2, 3]
stack.append(4)
stack.append(5)
print(stack)
print(stack.pop())
print(stack)
print(stack.pop())
print(stack)
OUTPUT:
List as a Queue:
Queue works on the principle of “First-in, first-out”. Below is list implementation of
queue. We use pop(0) to remove the first item from a list.
Program:
queue = [1,2,3]
queue.append(4)
queue.append(5)
print(queue)
print(queue.pop(0))
print(queue)
print(queue.pop(0))
print(queue)
OUTPUT:
Experiment-7
Implement programs to solve the problems using Python other data structures: Tuples and
Dictionaries
AIM: To write programs to define a dictionary and write programs to modify values, adding
new keys
PROGRAM:
i) Create a dictionary:
d1 = {}
d2 = {1:'a',2:'b',3:'c'}
d3 = {'a':'Hello','b':[1,2,3],'c':3}
d4 = dict([('a',10),('b',20)])
d5 = {1:'a',2:{'b':'two','c':'three'},3:'d'}
print(d1)
print(d2)
print(d3)
print(d4)
print(d4)
OUTPUT:
d["year"] = 2018
d["model"] = "Figo"
print(d)
OUTPUT:
iii) Adding new keys into a dictionary:
d={
'key1':'Welcome',
'key2':'CSE'
}
print(d)
d['key2'] = 'to'
d['key3'] = 'CSE'
print(d)
OUTPUT:
PROGRAM:
i) Iterate through keys:
statesAndCapitals = {
'Gujarat' : 'Gandhinagar',
'Maharashtra' : 'Mumbai',
'Rajasthan' : 'Jaipur',
'Bihar' : 'Patna'
}
OUTPUT:
Gujarat
Maharashtra
Rajasthan
Bihar
ii) Iterate through values:
statesAndCapitals = {
'Gujarat' : 'Gandhinagar',
'Maharashtra' : 'Mumbai',
'Rajasthan' : 'Jaipur',
'Bihar' : 'Patna'
}
OUTPUT:
List Of given capitals:
Gandhinagar
Mumbai
Jaipur
Patna
OUTPUT:
List Of given states and their capitals:
Gujarat : Gandhinagar
Maharashtra : Mumbai
Rajasthan : Jaipur
Bihar : Patna
METHODS:
->keys()
->values()
->items()
->pop()
->get()
->update()
->copy()
->clear()
PROGRAM:
d={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}
print(d.keys())
print(d.items())
print(d.values())
d.pop('Marks')
print(d)
d['Marks']=97
dict_new=d.copy()
print(dict_new)
print('Name: ', d.get('Name'))
print('Age: ', d.get('Age'))
d.update({'Age':22})
print(d)
d.clear()
print(d)
OUTPUT:
PROGRAM:
my_tuple = ()
print(my_tuple)
my_tuple = (1, 2, 3)
print(my_tuple)
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
OUTPUT:
PROGRAM:
Tuple operations:
fruits = "apple", "orange", "banana", "berry"
#indexing
print (fruits[0])
#addition
fruits=fruits+("mango",)
print(fruits)
#slicing
print(fruits[2:4])
#multiplication
print(fruits*3)
#in operator
print("berry" in fruits)
print("grapes" in fruits)
#length of tuple
print(len(fruits))
#max() and min()
print(max(fruits),min(fruits))
#deleting a tuple
del(fruits)
print(fruits)
OUTPUT:
Tuple comparisons:
cmp() method in Python compares two integers and returns -1, 0, 1 according
to comparison.
a = (1, 2, 3)
b = (1, 2, 5)
print(a < b)
a = (1, 2, 3, 4, 5)
b = (9, 8, 7, 6, 5)
print(set(a) & set(b))
a = (1, 2, 3, 4, 5)
b = (9, 8, 7, 6, 5)
a=set(a)
b=set(b)
print(a.intersection(b))
OUTPUT:
True
{5}
{5}
Experiment-8
Program:
class Dog:
a = "mammal"
b= "dog"
def fun(self):
print("I'm a", self.a)
print("I'm a", self.b)
Rodger = Dog()
print(Rodger.a)
Rodger.fun()
OUTPUT:
Program:
class user:
def __init__(self,name,age,gender):
self.name=name
self.age = age
self.gender = gender
def get_details(self):
print("Person details :")
print("\t Name :",self.name)
print("\t Age :",self.age)
print("\t Gender :",self.gender)
s=user("harry",20,"male")
s.get_details()
OUTPUT:
c)Understanding public and private members
AIM: To understand public and private members
Program:
class user:
def __init__(self,name,age,gender):
self.__name=name
self.__age = age
self.gender = gender
def get_details(self):
print("Person details :")
print("\t Name :",self.__name)
print("\t Age :",self.__age)
print("\t Gender :",self.gender)
def set_name(self,name):
self.__name = name
class Bank_Account(user):
def __init__(self,name,age,gender):
super().__init__(name,age,gender)
self.__balance=0
print("Hello!!! Welcome to the Deposit & Withdrawal Machine")
def get_user(self):
self.get_details()
s = Bank_Account("Harry",20,"Male")
s.get_user()
OUTPUT:
OUTPUT:
Program:
class emp:
name='Harsh'
salary='25000'
def show(self):
print (self.name)
print (self.salary)
e1 = emp()
# Use getattr instead of e1.name
e1.show()
print (getattr(e1,'name'))
# returns true if object has attribute
print (hasattr(e1,'name'))
setattr(e1,'height',152)
print (getattr(e1,'height'))
delattr(emp,'salary')
OUTPUT:
Experiment-9
a)Types of Inheritance in Python:
Aim: To implement different types of inheritance in Python
1. Single Inheritance:
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")
object = Child()
object.func1()
object.func2()
Output:
2. Multiple Inheritance :
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
# Base class2
class Father:
fathername = ""
def father(self):
print(self.fathername)
# Derived class
class Son(Mother, Father):
def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()
Output:
3. Multilevel Inheritance:
class Base:
# Intermediate class
class derived1(Base):
def __init__(self, derivedname, Basename):
self.derivedname = derivedname
# Derived class
class Son(derived):
def __init__(self,sonname, derivedname, Basename):
self.sonname = sonname
def print_name(self):
print('Base name :', self.Basename)
print("derived name :", self.derivedname)
print("Son name :", self.sonname)
4.Hierarchical Inheritance :
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")
# Derived class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
Output:
5.Hybrid Inheritance :
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")
class Student2(School):
def func3(self):
print("This function is in student 2.")
object = Student3()
object.func1()
object.func2()
OUTPUT:
class A():
def show(self):
print("This is from Class A.")
class B():
def show(self):
print("This is from Class B.")
obj_A = A()
obj_B = B()
obj_A.show()
obj_B.show()
Output:
Method Overriding:
class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")
class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")
class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
Output:
c) Abstract classes:
AIM: To implement program for abstract classes
class Human(Animal):
def move(self):
print("I can walk and run")
class Snake(Animal):
def move(self):
print("I can crawl")
class Dog(Animal):
def move(self):
print("I can bark")
class Lion(Animal):
def move(self):
print("I can roar")
R = Human()
R.move()
K = Snake()
K.move()
R = Dog()
R.move()
K = Lion()
K.move()
OUTPUT:
Experiment-10
Program:
result = x // y
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
divide(3, 0)
Output:
def test(x,y):
try:
print(x+y)
except (TypeError, ValueError) as e:
print(e)
test(‘a’,2)
OUTPUT:
c)Raising and Re-raising Exceptions
AIM: Program to Raise and Re-Raise exception
Program:
try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise
OUTPUT:
Re-raising exception:
Program:
def example():
try:
int('N/A')
except ValueError:
print("Didn't work")
raise
example()
OUTPUT:
d)Apply else and finally clause:
AIM: To apply else and finally clause
Program
(Else):
result = x // y
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
else:
print("Yeah ! Your answer is :", result)
divide(3, 2)
divide(3, 0)
OUTPUT:
(finally):
result = x // y
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
else:
print("Yeah ! Your answer is :", result)
finally:
print('This is always executed')
divide(3, 2)
divide(3, 0)
OUTPUT:
Program:
class complex:
def __init__(self, a, b):
self.a = a
self.b = b
Ob1 = complex(1, 2)
Ob2 = complex(2, 3)
Ob3 = Ob1 + Ob2
print("Result: ")
print(Ob3)
OUTPUT:
Experiment-11
# Inputs
import numpy as np
mylist = list('abcedfghijklmnopqrstuvwxyz')
myarr = np.arange(26)
# Solution
ser1 = pd.Series(mylist)
ser2 = pd.Series(myarr)
ser3 = pd.Series(mydict)
print(ser3.head())
a 0
b 1
c 2
d 4
e 3
dtype: int64
# Solution
df = ser.to_frame().reset_index()
print(df.head())
index 0
0 a 0
1 b 1
2 c 2
3 d 4
4 e 3
# Solution 1
df = pd.concat([ser1, ser2], axis=1)
# Solution 2
df = pd.DataFrame({'col1': ser1, 'col2': ser2})
print(df.head())
col1 col2
0 a 0
1 b 1
2 c 2
3 e 3
4 d 4
ser = pd.Series(list('abcedfghijklmnopqrstuvwxyz'))
# Solution
ser.name = 'alphabets'
ser.head()
0 a
1 b
2 c
3 e
4 d
# Solution
ser_u[~ser_u.isin(ser_i)]
0 1
1 2
2 3
5 6
6 7
7 8
dtype: int64
f)Get the minimum, 25th percentile, median, 75th, and max of a numeric series
# Input
state = np.random.RandomState(100)
# Solution
# Solution
ser.value_counts()
f 8
g 7
b 6
c 4
a 2
e 2
h 1
dtype: int64
# Input
ser = pd.Series(np.random.random(20))
print(ser.head())
# Solution
pd.qcut(ser, q=[0, .10, .20, .3, .4, .5, .6, .7, .8, .9, 1],
0 0.556912
1 0.892955
2 0.566632
3 0.146656
4 0.881579
dtype: float64
0 7th
1 9th
2 7th
3 3rd
4 8th
dtype: category
Categories (10, object): [1st < 2nd < 3rd < 4th ... 7th < 8th < 9th <
10th]
# Input
ser
# Solution
print(ser)
np.argwhere(ser % 3==0)
0 6
1 8
2 6
3 7
4 6
5 2
6 4
dtype: int64
array([[0],
[2],
[4]])
# Input
# Solution 1
# Solution 2
[5, 4, 0, 8]
Experiment-12
a.create a 1D array
arr = np.arange(10)
arr
#> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# Input
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# Solution
arr[arr % 2 == 1]
#> array([1, 3, 5, 7, 9])
c.Replace items that satisfy a condition without affecting the original array
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Desired Output:
#> array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])
arr[arr % 2 == 1] = -1
arr
#> array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])
d.Reshape an array
np.arange(10)
arr = np.arange(10)
arr.reshape(2, -1) # Setting to -1 automatically decides the number of cols
#> array([[0, 1, 2, 3, 4],
#> [5, 6, 7, 8, 9]])
# Method 2:
index = np.where(np.logical_and(a>=5, a<=10))
a[index]
#> (array([6, 9, 10]),)
# Method 3:
a[(a >= 5) & (a <= 10)]
# Solution
arr[:, [1,0,2]]
#> array([[1, 0, 2],
#> [4, 3, 5],
#> [7, 6, 8]])
g.Import a dataset with numbers and texts keeping the text intact in python
numpy
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
sepallength = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0])
# Solution
mu, med, sd = np.mean(sepallength), np.median(sepallength),
np.std(sepallength)
print(mu, med, sd)
#> 5.84333333333 5.8 0.825301291785
# Method 1
i, j = np.where(iris_2d)
# i, j contain the row numbers and column numbers of 600 elements of iris_x
np.random.seed(100)
iris_2d[np.random.choice((i), 20), np.random.choice((j), 20)] = np.nan
# Method 2
np.random.seed(100)
iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] =
np.nan
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')
# Solution
# Extract the species column as an array
species = np.array([row.tolist()[4] for row in iris])