Dataquest筆記

python中級

class

class Dataset:
        def __init__(self, data):
            self.header = data[0]
            self.data = data[1:]

其中,init要加雙下劃線,所有成員函數要有self參數。

try...except...

try:
        int('')
except [Exception as exc]:
        print("There was an error")
    [print(str(exc))]

global標識

global variable
variable =  xxx

正則表達式

re模塊

import re
"."         代表單個字符
"^xxx"  以xxx開頭
"xxx$"  以xxx結尾
“[abc]” abc均可
"|"     或
"{n}"       重復n次前一個re,例如年限:"[1-2][0-9]{3}"
"{m,n}" m到n個前一個re
“*”     0或多個RE, 盡量多ab* will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s. 
'+'     1或多個RE. ab+ will match ‘a’ followed by any non-zero number of ‘b’s; it will not match just ‘a’.
'?'     0或1個RE

re.search(regex, string)
re.sub(regex, repl, string, count=0, flags=0)
re.findall(pattern, string, flags=0)    例如:flags=re.IGNORECASE

python編譯器對于變量名稱解析的規則

LEGBE:local -> enclosing scope -> global -> build-ins -> throw an error

時間模塊

# Unix 時間模塊:1970年第一秒至今
import time
current_time = time.time()
current_struct_time = time.gmtime(current_time)
current_hour = current_struct_time.tm_hour
# 以上
tm_year: The year of the timestamp
tm_mon: The month of the timestamp (1-12)
tm_mday: The day in the month of the timestamp (1-31)
tm_hour: The hour of the timestamp (0-23)
tm_min: The minute of the timestamp (0-59)

# UTC 時間
import datetime
current_datetime = datetime.datetime.now()
current_year = current_datetime.year
current_month = current_datetime.month
# timedelta 模塊,用以計算相對時間,使用方法如下:
diff = datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
datetime1 = datetime1 +/- diff

# datetime輸出時間
datetime.strftime(“format”)
例如:
import datetime
mystery_date_formatted_string = mystery_date.strftime("%I:%M%p on %A %B %d, %Y")
print (mystery_date_formatted_string )

strftime格式詳見

# 將字符串轉為datetime對象
march3 = datetime.datetime.strptime("Mar 03, 2010", "%b %d, %Y")
# 將Unix時間轉為datetime對象
datetime.datetime.fromtimestamp(unix_timestamp)

numpy

核心數據類型是ndarray,即矩陣
import numpy as np
vector = np.array([5, 10, 15, 20])
matrix = np.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]])
data = np.genfromtxt("world_alcohol.csv", delimiter=',')

缺點:
* 單一數據中的各個元素必須是同一種類型
* 行列都只能用數字來索引

pandas

核心數據類型是dataframe,即二位的數據表。單個行列稱之為series。
import pandas as pd
food_info = pd.read_csv("food_info.csv")
food_info.head(5) #顯示前五行
column_names = food_info.columns # columns列名稱,索引類型,如需轉換可以用list()
datatypes = food_info.dtypes # columns數據類型
dimensions = food_info.shape

行列選擇

hundredth_row = food_info.loc[99]
hundredth_row = food_info.iloc[99]
iloc和loc的區別:loc使用索引編號,可以使用真值list和名稱進行索引,iloc只能使用數字。
columns = food_info[[column_name1,column_name2,...]]

Series計算

由于Series的數據類型本質上是ndarray,因此可以直接使用numpy進行計算。

使用索引

dataframe.set_index(keys=‘column_name’, drop=False/True)
將某列設置為索引之后,可以使用loc直接用列中的text數值進行和列名稱索引一樣的切片索引操作。

Datacleaning

  • 僅取部分列
    columns_needed = ["DBN", "rr_s", "rr_t", "rr_p", "N_s", "N_t", "N_p", "saf_p_11", "com_p_11", "eng_p_11", "aca_p_11", "saf_t_11", "com_t_11"]

    以下兩種表達所得結果相同

    survey = survey.loc[:, columns_needed]

    survey = survey[columns_needed]

  • 分別使用DataFrame和Series使用apply函數

    使用Series

    def pad_str(item):
    string = str(item)
    string = string.zfill(2)
    return string

    data['class_size']["padded_csd"] = data['class_size']["CSD"].apply(pad_str)
    data['class_size']["DBN"] = data['class_size']["padded_csd"] + data['class_size']["SCHOOL CODE"]

    def pad_str(column):
    if column.name == "CSD":
    for item in columns:
    string = str(item)
    item = string.zfill(2)
    return column

    data['class_size'] = data['class_size'].apply(pad_str, axis=1)
    data['class_size']["DBN"] = data['class_size']["padded_csd"] + data['class_size']["SCHOOL CODE"]

pandas字符串轉數字

pandas.to_numeric(),一定要加參數errors="coerce"。這樣遇到錯誤可以賦值為空。

pandas做圖

import matplotlib.pyplot as plt
DataFrame.plot.scatter(x='column name', y='column name')
plt.show()

pandas數據替換

pandas.Series.map()使用詞典進行數據替換
yes_no = {"Yes": True,No": False}
series = series.map(yes_no)

pandas更改列名稱

pandas.DataFrame.rename(),使用方法和map類似

pandas更改數據類型

pandas.DataFrame.astype()

命令行重命名文件

mv file1 file2
#當兩個文件處于同一路徑時即為重命名

命令行定義變量

OS=linux
OPERATING_SYSTEM="linux"
#變量等號兩邊一定不能有空格

使用export可以定義環境變量
export FOOD="Chicken and waffles"
環境變量可以使用os包打印
import os
print(os.environ["FOOD"])

從命令行執創建文件

touch xxx

echo流

echo "This is all a dream..." > dream.txt
echo "This is all a dream..." >> dream.txt
以上,第一種覆蓋原內容,第二種追加

從命令行執行python腳本

import sys
if __name__ == "__main__":
    XXXX
    print(sys.argv[0])
    print("Welcome to a Python script")

argv[0]為文件名,1之后為傳入的參數

source指令

可以將批處理命令放在一個文件中,然后使用source命令加載并執行。

pip指令

pip freeze #查看當前安裝包及其版本號

grep及管道

tail -n 10 logs.txt | grep "Error" #搜索最后10行中包含“Error”的行,文件頭部可用head
python rand.py | grep 9

git

git init
git branch branch_name
git checkout branch_name
git fetch
git add filename #添加到stage 
git commit操作的是本地庫,git push操作的是遠程庫。
git commit是將本地修改過的文件提交到本地庫中。
git push是將本地庫中的最新信息發送給遠程庫。
git merge 

使用API進行數據抓取

import requests
response = requests.get("url")
json = response.json()

json數據更改可以使用patch、put函數,刪除使用requests.delete("url")

使用beautifulsoup進行網頁數據抓取

from bs4 import BeautifulSoup
# Initialize the parser, and pass in the content we grabbed earlier.
parser = BeautifulSoup(content, 'html.parser')
body = parser.body
# Get a list of all occurrences of the body tag in the element.
body = parser.find_all("body")

# 使用CSS選擇器
parser.select("string")
其中 ,string前綴的#代表id,.代表class

SQLite

SELECT [columns]
FROM  [tables]
WHERE [conditions]
ORDER BY column1 [ASC or DESC][, column2 [ASC or DESC]]
LIMIT [number of results]
注意,limit應該在最后面

除了選擇操作,還有
INSERT -- adds new data.
UPDATE -- changes the values of some columns in existing data.
DELETE -- removes existing data.

INSERT INTO facts
VALUES (262, "dq", "DataquestLand", 60000, 40000, 20000, 500000, 100, 50, 10, 20, "2016-02-25 12:00:00", "2016-02-25 12:00:00");

UPDATE tableName
SET column1=value1, column2=value2, ...
WHERE column1=value3, column2=value4, ...

DELETE FROM tableName
WHERE column1=value1, column2=value2, ...;

# 查看數據類型
PRAGMA table_info(tableName);

# 增加列
ALTER TABLE tableName
ADD columnName dataType;

# 刪除列
ALTER TABLE tableName
DROP COLUMN columnName;

# 創建表
CREATE TABLE dbName.tableName(
column1 dataType1 PRIMARY KEY,
column2 dataType2,
column3 dataType3,
...
如果有foreign key則
foreign key(column3) reference table(column)
);

# 通過foreign key跨表查詢
SELECT [column1, column2, ...] from tableName1
INNER JOIN tableName2
ON tableName1.column3 == tableName2.column4;

sqlite3包的使用

連接和cursor的概念

import sqlite3
conn = sqlite3.connect("jobs.db")
cursor = conn.cursor()
query = "select Major,Major_category  from recent_grads;"
cursor.execute(query)
first_result = cursor.fetchone()
five_results = cursor.fetchmany(5)
all_results = cursor.fetchall()
conn.close()

SQLite和SQL支持的數據類型

SQLite的數據類型中沒有bool型,以整型代替。其支持的數據類型有:

  • NULL. 值是空值。
  • INTEGER. 值是有符號整數,根據值的大小以1,2,3,4,6 或8字節存儲。
  • REAL. 值是浮點數,以8字節 IEEE 浮點數存儲。
  • TEXT. 值是文本字符串,使用數據庫編碼(UTF-8, UTF-16BE 或 UTF-16LE)進行存儲。
  • BLOB. 值是一個數據塊,按它的輸入原樣存儲。

SQL支持的數據類型有:

  • bit 整型 bit 其值只能是0、1或空值。這種數據類型用于存儲只有兩種可能值的數據,如Yes 或No、True 或Fa lse 、On 或Off
  • int 整型 int -2147483648)到2147483 647之間的整數。占用4個字節
  • smallint 整型 -32768到32767之間的整數。占用2 字節空間
  • tinyint 整型 tinyint 0到255 之間的整數。占用1 個字節
  • numeric 精確數值型 numeric數據類型與decimal 型相同
  • decimal 精確數值型 decimal 數據類型能用來存儲從-1038-1到1038-1的固定精度和范圍的數值型數據。使用這種數據類型時,必須指定范圍和精度。 范圍是小數點左右所能存儲的數字的總位數。精度是小數點右邊存儲的數字的位數
  • money 貨幣型 表示錢和貨幣值。存儲從-9220億到9220 億之間的數據,精確到萬分之一
  • smallmoney 貨幣型 存儲從-214748.3648 到214748.3647 之間的數據,精確到萬分之一
  • float 近似數值型,供浮點數使用。說浮點數是近似的,是因為在其范圍內不是所有的數都能精確表示。浮點數可以是從-1.79E+308到1.79E+308 之間的任意數
  • real 近似數值型 表示數值在-3.40E+38到3.40E+38之間的浮點數
  • datetime 日期時間型 datetime數據類型用來表示日期和時間。精確到三百分之一秒或3.33毫秒
  • Smalldatetime 日期時間型 smalldatetime 表示從1900年1月1日到2079年6月6日間的日期和時間,精確到一分鐘
  • cursor 特殊數據型 包含一個對游標的引用。這種數據類型用在存儲過程中,而且創建表時不能用
  • timestamp 特殊數據型 用來創建一個數據庫范圍內的唯一數碼。 一個表中只能有一個timestamp列。每次插入或修改一行時,timestamp列的值都會改變。盡管它的名字中有“time”, 但timestamp列不是人們可識別的日期。在一個數據庫里,timestamp值是唯一的
  • Uniqueidentifier 特殊數據型,存儲一個全局唯一標識符,即GUID。GUID確實是全局唯一的。這個數幾乎沒有機會在另一個系統中被重建。可以使用NEWID 函數或轉換一個字符串為唯一標識符來初始化具有唯一標識符的列
  • char 字符型 存儲指定長度的定長非統一編碼型的數據。當定義一列為此類型時,你必須指定列長。當你總能知道要存儲的數據的長度時,此數據類型很有用。例如,當你按郵政編碼加4個字符格式來存儲數據時,你知道總要用到10個字符。此數據類型的列寬最大為8000 個字符
  • varchar 字符型 同char類型一樣,用來存儲非統一編碼型字符數據。與char 型不一樣,此數據類型為變長。當定義一列為該數據類型時,你要指定該列的最大長度。 它與char數據類型最大的區別是,存儲的長度不是列長,而是數據的長度
  • text 字符型 存儲大量的非統一編碼型字符數據
  • nchar 統一編碼字符型 存儲定長統一編碼字符型數據。統一編碼用雙字節結構來存儲每個字符,而不是用單字節(普通文本中的情況)。它允許大量的擴展字符。此數據類型能存儲4000種字符,使用的字節空間上增加了一倍
  • nvarchar 統一編碼字符型 用作變長的統一編碼字符型數據。此數據類型能存儲4000種字符,使用的字節空間增加了一倍
  • ntext 統一編碼字符型 存儲大量的統一編碼字符型數據。這種數據類型能存儲230 -1或將近10億個字符,且使用的字節空間增加了一倍
  • binary 二進制數據類型 存儲可達8000 字節長的定長的二進制數據。當輸入表的內容接近相同的長度時,你應該使用這種數據類型
  • varbinary 二進制數據類型 數據類型用來存儲可達8000 字節長的變長的二進制數據。當輸入表的內容大小可變時,你應該使用這種數據類型
  • image 二進制數據類型 存儲變長的二進制數據,最大可達231-1或大約20億字節

PostgreSQL數據庫

server-client模式的數據庫。
python庫操作:
import psycopg2
conn = psycopg2.connect("dbname=dq user=dq ")
cur = conn.cursor()
cur.execute("command")
print(cur)
conn.close()

命令行操作:
啟動:psql
退出:\q
創建數據庫:CREATE DATABASE dbName;
\l -- list all available databases.
\dt -- list all tables in the current database.
\du -- list users.
連接到數據庫:psql -d database

# 用戶及權限管理
CREATE ROLE userName [WITH CREATEDB LOGIN PASSWORD 'password'];
GRANT SELECT, INSERT, UPDATE, DELETE ON tableName TO    userName;
REVOKE SELECT, INSERT, UPDATE, DELETE ON tableName FROM userName;

CREATE ROLE userName WITH LOGIN PASSWORD 'password' SUPERUSER;

安裝 下載

conda install psycopg2
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,923評論 18 139
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,765評論 18 399
  • 國家電網公司企業標準(Q/GDW)- 面向對象的用電信息數據交換協議 - 報批稿:20170802 前言: 排版 ...
    庭說閱讀 11,149評論 6 13
  • 親愛的李狗蛋: 我很想你, 上班路上想啊想啊就遲到了, 工作時候想啊想啊就加班了, 吃飯時間想啊想啊就飽了。 想啊...
    小小俠閱讀 398評論 0 0
  • 班里剛轉來一個同學,可能不太適應,上課聽講不專注,做題很慢錯的還不少,怎么辦呢?我著急。 星期一的數學課上,一道題...
    娟秀人生閱讀 526評論 1 0