python中級(jí)
class
class Dataset:
def __init__(self, data):
self.header = data[0]
self.data = data[1:]
其中虑润,init要加雙下劃線,所有成員函數(shù)要有self參數(shù)加酵。
try...except...
try:
int('')
except [Exception as exc]:
print("There was an error")
[print(str(exc))]
global標(biāo)識(shí)
global variable
variable = xxx
正則表達(dá)式
re模塊
import re
"." 代表單個(gè)字符
"^xxx" 以xxx開(kāi)頭
"xxx$" 以xxx結(jié)尾
“[abc]” abc均可
"|" 或
"{n}" 重復(fù)n次前一個(gè)re拳喻,例如年限:"[1-2][0-9]{3}"
"{m,n}" m到n個(gè)前一個(gè)re
“*” 0或多個(gè)RE, 盡量多ab* will match ‘a(chǎn)’, ‘a(chǎn)b’, or ‘a(chǎn)’ followed by any number of ‘b’s.
'+' 1或多個(gè)RE. ab+ will match ‘a(chǎn)’ followed by any non-zero number of ‘b’s; it will not match just ‘a(chǎn)’.
'?' 0或1個(gè)RE
re.search(regex, string)
re.sub(regex, repl, string, count=0, flags=0)
re.findall(pattern, string, flags=0) 例如:flags=re.IGNORECASE
python編譯器對(duì)于變量名稱解析的規(guī)則
LEGBE:local -> enclosing scope -> global -> build-ins -> throw an error
時(shí)間模塊
# Unix 時(shí)間模塊: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 時(shí)間
import datetime
current_datetime = datetime.datetime.now()
current_year = current_datetime.year
current_month = current_datetime.month
# timedelta 模塊,用以計(jì)算相對(duì)時(shí)間猪腕,使用方法如下:
diff = datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
datetime1 = datetime1 +/- diff
# datetime輸出時(shí)間
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 )
# 將字符串轉(zhuǎn)為datetime對(duì)象
march3 = datetime.datetime.strptime("Mar 03, 2010", "%b %d, %Y")
# 將Unix時(shí)間轉(zhuǎn)為datetime對(duì)象
datetime.datetime.fromtimestamp(unix_timestamp)
numpy
核心數(shù)據(jù)類型是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=',')
缺點(diǎn):
* 單一數(shù)據(jù)中的各個(gè)元素必須是同一種類型
* 行列都只能用數(shù)字來(lái)索引
pandas
核心數(shù)據(jù)類型是dataframe,即二位的數(shù)據(jù)表陋葡。單個(gè)行列稱之為series亚亲。
import pandas as pd
food_info = pd.read_csv("food_info.csv")
food_info.head(5) #顯示前五行
column_names = food_info.columns # columns列名稱,索引類型腐缤,如需轉(zhuǎn)換可以用list()
datatypes = food_info.dtypes # columns數(shù)據(jù)類型
dimensions = food_info.shape
行列選擇
hundredth_row = food_info.loc[99]
hundredth_row = food_info.iloc[99]
iloc和loc的區(qū)別:loc使用索引編號(hào)捌归,可以使用真值list和名稱進(jìn)行索引,iloc只能使用數(shù)字岭粤。
columns = food_info[[column_name1,column_name2,...]]
Series計(jì)算
由于Series的數(shù)據(jù)類型本質(zhì)上是ndarray惜索,因此可以直接使用numpy進(jìn)行計(jì)算。
使用索引
dataframe.set_index(keys=‘column_name’, drop=False/True)
將某列設(shè)置為索引之后剃浇,可以使用loc直接用列中的text數(shù)值進(jìn)行和列名稱索引一樣的切片索引操作巾兆。
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"]以下兩種表達(dá)所得結(jié)果相同
survey = survey.loc[:, columns_needed]
survey = survey[columns_needed]
-
分別使用DataFrame和Series使用apply函數(shù)
使用Series
def pad_str(item):
string = str(item)
string = string.zfill(2)
return stringdata['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 columndata['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字符串轉(zhuǎn)數(shù)字
pandas.to_numeric(),一定要加參數(shù)errors="coerce"偿渡。這樣遇到錯(cuò)誤可以賦值為空臼寄。
pandas做圖
import matplotlib.pyplot as plt
DataFrame.plot.scatter(x='column name', y='column name')
plt.show()
pandas數(shù)據(jù)替換
pandas.Series.map()使用詞典進(jìn)行數(shù)據(jù)替換
yes_no = {"Yes": True,No": False}
series = series.map(yes_no)
pandas更改列名稱
pandas.DataFrame.rename(),使用方法和map類似
pandas更改數(shù)據(jù)類型
pandas.DataFrame.astype()
命令行重命名文件
mv file1 file2
#當(dāng)兩個(gè)文件處于同一路徑時(shí)即為重命名
命令行定義變量
OS=linux
OPERATING_SYSTEM="linux"
#變量等號(hào)兩邊一定不能有空格
使用export可以定義環(huán)境變量
export FOOD="Chicken and waffles"
環(huán)境變量可以使用os包打印
import os
print(os.environ["FOOD"])
從命令行執(zhí)創(chuàng)建文件
touch xxx
echo流
echo "This is all a dream..." > dream.txt
echo "This is all a dream..." >> dream.txt
以上溜宽,第一種覆蓋原內(nèi)容吉拳,第二種追加
從命令行執(zhí)行python腳本
import sys
if __name__ == "__main__":
XXXX
print(sys.argv[0])
print("Welcome to a Python script")
argv[0]為文件名,1之后為傳入的參數(shù)
source指令
可以將批處理命令放在一個(gè)文件中适揉,然后使用source命令加載并執(zhí)行留攒。
pip指令
pip freeze #查看當(dāng)前安裝包及其版本號(hào)
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操作的是本地庫(kù)嫉嘀,git push操作的是遠(yuǎn)程庫(kù)炼邀。
git commit是將本地修改過(guò)的文件提交到本地庫(kù)中。
git push是將本地庫(kù)中的最新信息發(fā)送給遠(yuǎn)程庫(kù)剪侮。
git merge
使用API進(jìn)行數(shù)據(jù)抓取
import requests
response = requests.get("url")
json = response.json()
json數(shù)據(jù)更改可以使用patch拭宁、put函數(shù)洛退,刪除使用requests.delete("url")
使用beautifulsoup進(jìn)行網(wǎng)頁(yè)數(shù)據(jù)抓取
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應(yīng)該在最后面
除了選擇操作,還有
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, ...;
# 查看數(shù)據(jù)類型
PRAGMA table_info(tableName);
# 增加列
ALTER TABLE tableName
ADD columnName dataType;
# 刪除列
ALTER TABLE tableName
DROP COLUMN columnName;
# 創(chuàng)建表
CREATE TABLE dbName.tableName(
column1 dataType1 PRIMARY KEY,
column2 dataType2,
column3 dataType3,
...
如果有foreign key則
foreign key(column3) reference table(column)
);
# 通過(guò)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支持的數(shù)據(jù)類型
SQLite的數(shù)據(jù)類型中沒(méi)有bool型腔剂,以整型代替媒区。其支持的數(shù)據(jù)類型有:
- NULL. 值是空值。
- INTEGER. 值是有符號(hào)整數(shù)掸犬,根據(jù)值的大小以1袜漩,2,3湾碎,4宙攻,6 或8字節(jié)存儲(chǔ)。
- REAL. 值是浮點(diǎn)數(shù)胜茧,以8字節(jié) IEEE 浮點(diǎn)數(shù)存儲(chǔ)粘优。
- TEXT. 值是文本字符串,使用數(shù)據(jù)庫(kù)編碼(UTF-8, UTF-16BE 或 UTF-16LE)進(jìn)行存儲(chǔ)呻顽。
- BLOB. 值是一個(gè)數(shù)據(jù)塊雹顺,按它的輸入原樣存儲(chǔ)。
SQL支持的數(shù)據(jù)類型有:
- bit 整型 bit 其值只能是0廊遍、1或空值嬉愧。這種數(shù)據(jù)類型用于存儲(chǔ)只有兩種可能值的數(shù)據(jù),如Yes 或No喉前、True 或Fa lse 没酣、On 或Off
- int 整型 int -2147483648)到2147483 647之間的整數(shù)。占用4個(gè)字節(jié)
- smallint 整型 -32768到32767之間的整數(shù)卵迂。占用2 字節(jié)空間
- tinyint 整型 tinyint 0到255 之間的整數(shù)裕便。占用1 個(gè)字節(jié)
- numeric 精確數(shù)值型 numeric數(shù)據(jù)類型與decimal 型相同
- decimal 精確數(shù)值型 decimal 數(shù)據(jù)類型能用來(lái)存儲(chǔ)從-1038-1到1038-1的固定精度和范圍的數(shù)值型數(shù)據(jù)。使用這種數(shù)據(jù)類型時(shí)见咒,必須指定范圍和精度偿衰。 范圍是小數(shù)點(diǎn)左右所能存儲(chǔ)的數(shù)字的總位數(shù)。精度是小數(shù)點(diǎn)右邊存儲(chǔ)的數(shù)字的位數(shù)
- money 貨幣型 表示錢和貨幣值改览。存儲(chǔ)從-9220億到9220 億之間的數(shù)據(jù)下翎,精確到萬(wàn)分之一
- smallmoney 貨幣型 存儲(chǔ)從-214748.3648 到214748.3647 之間的數(shù)據(jù),精確到萬(wàn)分之一
- float 近似數(shù)值型宝当,供浮點(diǎn)數(shù)使用视事。說(shuō)浮點(diǎn)數(shù)是近似的,是因?yàn)樵谄浞秶鷥?nèi)不是所有的數(shù)都能精確表示庆揩。浮點(diǎn)數(shù)可以是從-1.79E+308到1.79E+308 之間的任意數(shù)
- real 近似數(shù)值型 表示數(shù)值在-3.40E+38到3.40E+38之間的浮點(diǎn)數(shù)
- datetime 日期時(shí)間型 datetime數(shù)據(jù)類型用來(lái)表示日期和時(shí)間俐东。精確到三百分之一秒或3.33毫秒
- Smalldatetime 日期時(shí)間型 smalldatetime 表示從1900年1月1日到2079年6月6日間的日期和時(shí)間跌穗,精確到一分鐘
- cursor 特殊數(shù)據(jù)型 包含一個(gè)對(duì)游標(biāo)的引用。這種數(shù)據(jù)類型用在存儲(chǔ)過(guò)程中虏辫,而且創(chuàng)建表時(shí)不能用
- timestamp 特殊數(shù)據(jù)型 用來(lái)創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)范圍內(nèi)的唯一數(shù)碼瞻离。 一個(gè)表中只能有一個(gè)timestamp列。每次插入或修改一行時(shí)乒裆,timestamp列的值都會(huì)改變。盡管它的名字中有“time”推励, 但timestamp列不是人們可識(shí)別的日期鹤耍。在一個(gè)數(shù)據(jù)庫(kù)里,timestamp值是唯一的
- Uniqueidentifier 特殊數(shù)據(jù)型验辞,存儲(chǔ)一個(gè)全局唯一標(biāo)識(shí)符稿黄,即GUID。GUID確實(shí)是全局唯一的跌造。這個(gè)數(shù)幾乎沒(méi)有機(jī)會(huì)在另一個(gè)系統(tǒng)中被重建杆怕。可以使用NEWID 函數(shù)或轉(zhuǎn)換一個(gè)字符串為唯一標(biāo)識(shí)符來(lái)初始化具有唯一標(biāo)識(shí)符的列
- char 字符型 存儲(chǔ)指定長(zhǎng)度的定長(zhǎng)非統(tǒng)一編碼型的數(shù)據(jù)壳贪。當(dāng)定義一列為此類型時(shí)陵珍,你必須指定列長(zhǎng)。當(dāng)你總能知道要存儲(chǔ)的數(shù)據(jù)的長(zhǎng)度時(shí)违施,此數(shù)據(jù)類型很有用互纯。例如,當(dāng)你按郵政編碼加4個(gè)字符格式來(lái)存儲(chǔ)數(shù)據(jù)時(shí)磕蒲,你知道總要用到10個(gè)字符留潦。此數(shù)據(jù)類型的列寬最大為8000 個(gè)字符
- varchar 字符型 同char類型一樣,用來(lái)存儲(chǔ)非統(tǒng)一編碼型字符數(shù)據(jù)辣往。與char 型不一樣兔院,此數(shù)據(jù)類型為變長(zhǎng)。當(dāng)定義一列為該數(shù)據(jù)類型時(shí)站削,你要指定該列的最大長(zhǎng)度坊萝。 它與char數(shù)據(jù)類型最大的區(qū)別是,存儲(chǔ)的長(zhǎng)度不是列長(zhǎng)钻哩,而是數(shù)據(jù)的長(zhǎng)度
- text 字符型 存儲(chǔ)大量的非統(tǒng)一編碼型字符數(shù)據(jù)
- nchar 統(tǒng)一編碼字符型 存儲(chǔ)定長(zhǎng)統(tǒng)一編碼字符型數(shù)據(jù)屹堰。統(tǒng)一編碼用雙字節(jié)結(jié)構(gòu)來(lái)存儲(chǔ)每個(gè)字符,而不是用單字節(jié)(普通文本中的情況)街氢。它允許大量的擴(kuò)展字符扯键。此數(shù)據(jù)類型能存儲(chǔ)4000種字符,使用的字節(jié)空間上增加了一倍
- nvarchar 統(tǒng)一編碼字符型 用作變長(zhǎng)的統(tǒng)一編碼字符型數(shù)據(jù)珊肃。此數(shù)據(jù)類型能存儲(chǔ)4000種字符荣刑,使用的字節(jié)空間增加了一倍
- ntext 統(tǒng)一編碼字符型 存儲(chǔ)大量的統(tǒng)一編碼字符型數(shù)據(jù)馅笙。這種數(shù)據(jù)類型能存儲(chǔ)230 -1或?qū)⒔?0億個(gè)字符,且使用的字節(jié)空間增加了一倍
- binary 二進(jìn)制數(shù)據(jù)類型 存儲(chǔ)可達(dá)8000 字節(jié)長(zhǎng)的定長(zhǎng)的二進(jìn)制數(shù)據(jù)厉亏。當(dāng)輸入表的內(nèi)容接近相同的長(zhǎng)度時(shí)董习,你應(yīng)該使用這種數(shù)據(jù)類型
- varbinary 二進(jìn)制數(shù)據(jù)類型 數(shù)據(jù)類型用來(lái)存儲(chǔ)可達(dá)8000 字節(jié)長(zhǎng)的變長(zhǎng)的二進(jìn)制數(shù)據(jù)。當(dāng)輸入表的內(nèi)容大小可變時(shí)爱只,你應(yīng)該使用這種數(shù)據(jù)類型
- image 二進(jìn)制數(shù)據(jù)類型 存儲(chǔ)變長(zhǎng)的二進(jìn)制數(shù)據(jù)皿淋,最大可達(dá)231-1或大約20億字節(jié)
PostgreSQL數(shù)據(jù)庫(kù)
server-client模式的數(shù)據(jù)庫(kù)。
python庫(kù)操作:
import psycopg2
conn = psycopg2.connect("dbname=dq user=dq ")
cur = conn.cursor()
cur.execute("command")
print(cur)
conn.close()
命令行操作:
啟動(dòng):psql
退出:\q
創(chuàng)建數(shù)據(jù)庫(kù):CREATE DATABASE dbName;
\l -- list all available databases.
\dt -- list all tables in the current database.
\du -- list users.
連接到數(shù)據(jù)庫(kù):psql -d database
# 用戶及權(quán)限管理
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