栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

About Crash Course in Python and SciPy

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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.
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/932404.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号