Part1_Cours_Python
Part1_Cours_Python
Part1_Cours_Python
Teach the
machine
some
features
Supervised ML
Teach the
machine
Thesome
machine can
learn by itself and
features
predicts a
solution/result
Outline
This notation works for just about anything, including object methods:
In [3]: L = [1, 2, 3]
In [4]: L.insert?
Type: builtin_function_or_method
String form: <built-in method insert of list object at 0x1024b8ea8>
Docstring: L.insert(index, object) -- insert object before index
For example, imagine you've created a myscript.py file with the following contents:
#----------- # file: myscript.py
def square(x):
"""square a number"""
return x ** 2
1 squared is 1
for N in range(1, 4):
print(N, "squared is", square(N))
2 squared is 4
3 squared is 9
You can execute this from your IPython session as follows:
In [6]: %run myscript.py
Timing Code Execution: %timeit
In [9]: %%timeit
...: L = []
...: for n in range(1000):
...: L.append(n ** 2)
...:
1000 loops, best of 3: 373 µs per loop
In [6]: print(In[1])
Data types: Python Integer
x = 1
• Python is coded in C
struct _longobject {
long ob_refcnt;
PyTypeObject *ob_type;
size_t ob_size;
long ob_digit[1];
};
A single integer in Python 3.4 actually contains four pieces:
•ob_refcnt, a reference count that helps Python silently handle memory allocation
and deallocation
•ob_type, which encodes the type of the variable
•ob_size, which specifies the size of the following data members
•ob_digit, which contains the actual integer value that we expect the Python variable
to represent.
Data types: Python List
Heterogenous list
List of strings
The Python list, contains a pointer to a
block of pointers, each of which in turn
points to a full Python object like the
Python integer we saw earlier
The array essentially contains a single
pointer to one contiguous block of data
Arrays from scratch
Numpy data types
The Basics of NumPy Arrays¶
• NumPy Array Attributes
Array indexing
Array Slicing: Accessing Subarrays
Just as we can use square brackets to
access individual array elements, we can
also use them to access subarrays with
the slice notation, marked by the colon (:)
character. The NumPy slicing syntax
follows that of the standard Python list; to
access a slice of an array x, use this:
x[start:stop:step]
If any of these are unspecified, they
default to the values start=0, stop=size of
dimension, step=1. We'll take a look at
accessing sub-arrays in one dimension and
in multiple dimensions.
x[5::-2]
Array Slicing: Accessing Subarrays
• Array slices return views rather
than copies of the array data. This is one
area in which NumPy array slicing differs
from Python list slicing: in lists, slices will be
copies.
Reshaping of Arrays Concatenate
The most flexible way of doing this is with
the reshape method. For example, if you want to put
the numbers 1 through 9 in a 3×3 grid, you can do the
following
• Trigonometric operations
• Aggregate
ix indexer
Masking and fancy indexing Ufuncs
Time taken for operation as an object NaN - data virus
NaN in Pandas
Typeclass Conversion When Storing NAs NA Sentinel Value
floating No change np.nan
object No change None or np.nan
integer Cast to float64 np.nan
boolean Cast to object None or np.nan
Example
Operating on NaN values
• show() or plt.show()
It needs to be done only once per kernel/session è Embeded PNG plot per Kernel
Plot and save to file MATLAB-style Interface
Object-oriented interface
The object-oriented interface is available for these more complicated situations, and for when you want
more control over your figure. Rather than depending on some notion of an "active" figure or axes, in the
object-oriented interface the plotting functions are methods of explicit Figure and Axes objects.
The choice of which style to use is largely a matter of preference, but the object-
oriented approach can become a necessity as plots become more complicated.
Set Figure
• fig, ax = plt.subplots(3,2)
• ax[0,1].plot(x, y1, color = 'r', linestyle = '--')
• ax[1,1].plot(x, y2, color = 'b', linestyle = '-.')
• ax[0,1].plot(x, y1, color = 'r', linestyle = '--')
• ax[1,1].plot(x, y2, color = 'b', linestyle = '-.')
Line Colors and Style
Set ax limits, labels
plt.plot() → ax.plot(),
plt.legend() → ax.legend()
•plt.xlabel() → ax.set_xlabel()
•plt.ylabel() → ax.set_ylabel()
•plt.xlim() → ax.set_xlim()
•plt.ylim() → ax.set_ylim()
•plt.title() → ax.set_title()
Plot Scatter
Contour Plot
Histograms