About Crash Course in Python and SciPy

1.1 Python Crash Course

When getting started in Python you need to know a few key details about the language syntax to be able to read and understand Python code. This includes:

  • Assigment
  • Flow Control
  • Data Structure
  • Functions

We will cover each of these topics in turn with small standalone examples that you can type and run. Remember, whitespace has meaning in Python.

1.1.1 Assignment

As a programmer, assignment and types should not be surprising to you.

# Strings
data = "Hello world"
print(data[0])
print(len(data))
print(data)

# Numbers
value = 123.1
print(value)
value = 10
print(value)

# Boolean
a = True
b = False
print(a, b)

# Multiple Assignment
a, b, c = 1, 2, 3
print(a, b, c)

# No Value
a = None
print(a)

 1.1.2 Flow Control

 There are three main types of flow control that you need to learn:

  • If-Then-Else conditions
  • For-Loops
  • While-Loops

Notice the colon (:) at the end of the condition and the meaningful tab intend for the code block under the condition. Running the example prints:

If-Then-Else conditional

#If-Then-Else Conditional
value = 99
if value == 99:
    print('That is fast')
elif value > 200:
    print("That is too fast")
else:
    print("That is safe")


# For -Loop
for i in range(10):
    print(i)



# While-Loop
i = 0
while i < 10:
    print(i)
    i += 1

1.1.3 Data Structures

There are three data structures in Python that you will find the most used and useful. They are tuples, lists and dictionaries.

# Tuple 
# Tuples are read-only collections of items
a = (1, 2, 3)
print(a)



# List
# Lists use the square bracket notation and can be index using array notation
mylist = [1, 2, 3]
print("Zeroth Value: %d" % mylist[0])
mylist.append(4)
print("List Length: %d" % len(mylist))
for value in mylist:
    print(value)


# Dictionary
# Dictionaries are mapping of names to values,like key-value pairs.Note the use of the curly bracket and colon notations when defining the dictionary.
mydict = {'a': 1, 'b': 2, 'c':3}
print("A value: %d" % mydict['a'])

mydict['a'] = 11
print("A value: %d" % mydict['a'])

print("Keys: %s" % mydict.keys())

print("Values: %s" % mydict.values())

for key in mydict.keys():
    print(mydict[key])


# Functions
# The biggest gotcha with Python is the whitespace. Ensure that you have an empty new line
# after indented code. The example below defines a new function to calculate the sum of two
# values and calls the function with two arguments.
# Sum function
def mysum(x, y):
    return x + y

# Test sum function
result = mysum(1, 3)
print(result)


1.2 NumPy Crash Course

NumPy provides the foundation data structures and operations for SciPy. These are arrays (ndarrays) that are efficient to define and manipulate.

# Example of creating a Numpy array
# Notice how we easily converted a Python list to a NumPy array.
# Create Array
import numpy as np
mylist = [1, 2, 3]
myarray = np.array(mylist)
print(myarray)
print(myarray.shape)


# Access Data
# Array notation and ranges can be used to efficiently access data in a NumPy array.
# access values
import numpy as np
mylist = [[1, 2, 3], [3, 4, 5]]
myarray = np.array(mylist)
print(myarray)
print(myarray.shape)
print("First row: %s" % myarray[0])
print("Last row: %s" % myarray[-1])
print("Specific row and col: %s" % myarray[0, 2])
print("Whole col: %s" % myarray[:, 2])


# Arithnetic
# Numpy arrays can be used directly in arithmetic
# arithmetic
import numpy as np
myarray1 = np.array([2, 2, 2])
myarray2 = np.array([3, 3, 3])
print("Addition: %s" %(myarray1 + myarray2))
print("Multiplication: %s" %(myarray1 * myarray2))

 There is a lot more to NumPy arrays but these examples give you a flavor of the efficiencies they provide when working with lots of numerical data. See Chapter 24 for resources to learn more about the NumPy API.

1.3 Matplotlib Crash Course

Matplotlib can be used for creating plots and charts. The library is generally used as follows:

  • Call a plotting function with some data (e.g. .plot()).
  • Call many functions to setup the properties of the plot (e.g. labels and colors).
  • Make the plot visible (e.g. .show()).

1.3.1 Line Plot

The example below creates a simple line plot from one dimensional data.

# basic line plot
import matplotlib.pyplot as plt
import numpy as np
myarray = np.array([1, 2, 3])
plt.plot(myarray)
plt.xlabel('some x axis')
plt.ylabel('some y axis')
plt.show()

 1.3.2 Scatter Plot

Below is a simple example of creating a scatter plot from two dimensional data.

# basic scatter plot
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1, 2, 3])
y = np.array([2, 4, 6])
plt.scatter(x, y)
plt.xlabel('some x axis')
plt.ylabel('some y axis')
plt.show()

1.4 Panda Crash Course

Pandas provides data structures and functionality to quickly manipulate and analyze data. The key to understanding Pandas for machine learning is understanding the Series and DataFrame data structures.

1.4.1 Series

A series is a one dimensional array where the rows and columns can be labeled.

# series
import numpy as np
import pandas as pd
myarray = np.array([1, 2, 3])
rownames = ['a','b','c']
myseries = pd.Series(myarray, index=rownames)
print(myseries)

 

 

You can access the data in a series like a NumPy array and like a dictionary, for example:

print(myseries[0])
print(myseries['a'])

1.4.2 DataFrame

A data frame is a multi-dimensional array where the rows and the columns can be labeled.

# dataframe
import numpy as np
import pandas as pd
myarray = np.array([[1, 2, 3],[4, 5, 6]])
rownames = ['a','b']
colnames = ['one','two','three']
mydataframe = pd.DataFrame(myarray, index=rownames, columns=colnames)
print(mydataframe)

Data can be index using column names.

print("method 1:")
print("one column: %s" % mydataframe['one'])
print("method 2:")
print("one column: %s" % mydataframe.one)

Pandas is a very powerful tool for slicing and dicing you data. See Chapter 24 for resources to learn more about the Pandas API.

1.5 Summary

You have covered a lot of ground in this lesson. You discovered basic syntax and usage of Python and three key Python libraries used for machine learning:

  • NumPy.
  • Matplotlib.
  • Pandas.
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值