
Python運(yùn)用于數(shù)據(jù)分析的簡單教程
這篇文章主要介紹了Python運(yùn)用于數(shù)據(jù)分析的簡單教程,主要介紹了如何運(yùn)用Python來進(jìn)行數(shù)據(jù)導(dǎo)入、變化、統(tǒng)計(jì)和假設(shè)檢驗(yàn)等基本的數(shù)據(jù)分析,需要的朋友可以參考下
我這里來分享一下如何通過Python來開始數(shù)據(jù)分析。具體內(nèi)容如下:
數(shù)據(jù)導(dǎo)入
導(dǎo)入本地的或者web端的CSV文件;
數(shù)據(jù)變換;
數(shù)據(jù)統(tǒng)計(jì)描述;
假設(shè)檢驗(yàn)
單樣本t檢驗(yàn);
可視化;
創(chuàng)建自定義函數(shù)。
數(shù)據(jù)導(dǎo)入
這是很關(guān)鍵的一步,為了后續(xù)的分析我們首先需要導(dǎo)入數(shù)據(jù)。通常來說,數(shù)據(jù)是CSV格式,就算不是,至少也可以轉(zhuǎn)換成CSV格式。在Python中,我們的操作如下:
import pandas as pd
# Reading data locally
df = pd.read_csv('/Users/al-ahmadgaidasaad/Documents/d.csv')
# Reading data from web
data_url = "https://raw.githubusercontent.com/alstat/Analysis-with-Programming/master/2014/Python/Numerical-Descriptions-of-the-Data/data.csv"
df = pd.read_csv(data_url)
為了讀取本地CSV文件,我們需要pandas這個(gè)數(shù)據(jù)分析庫中的相應(yīng)模塊。其中的read_csv函數(shù)能夠讀取本地和web數(shù)據(jù)。
數(shù)據(jù)變換
既然在工作空間有了數(shù)據(jù),接下來就是數(shù)據(jù)變換。統(tǒng)計(jì)學(xué)家和科學(xué)家們通常會在這一步移除分析中的非必要數(shù)據(jù)。我們先看看數(shù)據(jù):
# Head of the data
print df.head()
# OUTPUT
Abra Apayao Benguet Ifugao Kalinga
0 1243 2934 148 3300 10553
1 4158 9235 4287 8063 35257
2 1787 1922 1955 1074 4544
3 17152 14501 3536 19607 31687
4 1266 2385 2530 3315 8520
# Tail of the data
print df.tail()
# OUTPUT
Abra Apayao Benguet Ifugao Kalinga
74 2505 20878 3519 19737 16513
75 60303 40065 7062 19422 61808
76 6311 6756 3561 15910 23349
77 13345 38902 2583 11096 68663
78 2623 18264 3745 16787 16900
對R語言程序員來說,上述操作等價(jià)于通過print(head(df))來打印數(shù)據(jù)的前6行,以及通過print(tail(df))來打印數(shù)據(jù)的后6行。當(dāng)然Python中,默認(rèn)打印是5行,而R則是6行。因此R的代碼head(df, n = 10),在Python中就是df.head(n = 10),打印數(shù)據(jù)尾部也是同樣道理。
在R語言中,數(shù)據(jù)列和行的名字通過colnames和rownames來分別進(jìn)行提取。在Python中,我們則使用columns和index屬性來提取,如下:
# Extracting column names
print df.columns
# OUTPUT
Index([u'Abra', u'Apayao', u'Benguet', u'Ifugao', u'Kalinga'], dtype='object')
# Extracting row names or the index
print df.index
# OUTPUT
Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78], dtype='int64')
數(shù)據(jù)轉(zhuǎn)置使用T方法,
# Transpose data
print df.T
# OUTPUT
0 1 2 3 4 5 6 7 8 9
Abra 1243 4158 1787 17152 1266 5576 927 21540 1039 5424
Apayao 2934 9235 1922 14501 2385 7452 1099 17038 1382 10588
Benguet 148 4287 1955 3536 2530 771 2796 2463 2592 1064
Ifugao 3300 8063 1074 19607 3315 13134 5134 14226 6842 13828
Kalinga 10553 35257 4544 31687 8520 28252 3106 36238 4973 40140
... 69 70 71 72 73 74 75 76 77
Abra ... 12763 2470 59094 6209 13316 2505 60303 6311 13345
Apayao ... 37625 19532 35126 6335 38613 20878 40065 6756 38902
Benguet ... 2354 4045 5987 3530 2585 3519 7062 3561 2583
Ifugao ... 9838 17125 18940 15560 7746 19737 19422 15910 11096
Kalinga ... 65782 15279 52437 24385 66148 16513 61808 23349 68663
78
Abra 2623
Apayao 18264
Benguet 3745
Ifugao 16787
Kalinga 16900
其他變換,例如排序就是用sort屬性?,F(xiàn)在我們提取特定的某列數(shù)據(jù)。Python中,可以使用iloc或者ix屬性。但是我更喜歡用ix,因?yàn)樗€(wěn)定一些。假設(shè)我們需數(shù)據(jù)第一列的前5行,我們有:
print df.ix[:, 0].head()
# OUTPUT
0 1243
1 4158
2 1787
3 17152
4 1266
Name: Abra, dtype: int64
順便提一下,Python的索引是從0開始而非1。為了取出從11到20行的前3列數(shù)據(jù),我們有:
print df.ix[10:20, 0:3]
# OUTPUT
Abra Apayao Benguet
10 981 1311 2560
11 27366 15093 3039
12 1100 1701 2382
13 7212 11001 1088
14 1048 1427 2847
15 25679 15661 2942
16 1055 2191 2119
17 5437 6461 734
18 1029 1183 2302
19 23710 12222 2598
20 1091 2343 2654
上述命令相當(dāng)于df.ix[10:20, ['Abra', 'Apayao', 'Benguet']]。
為了舍棄數(shù)據(jù)中的列,這里是列1(Apayao)和列2(Benguet),我們使用drop屬性,如下:
print df.drop(df.columns[[1, 2]], axis = 1).head()
# OUTPUT
Abra Ifugao Kalinga
0 1243 3300 10553
1 4158 8063 35257
2 1787 1074 4544
3 17152 19607 31687
4 1266 3315 8520
axis 參數(shù)告訴函數(shù)到底舍棄列還是行。如果axis等于0,那么就舍棄行。
統(tǒng)計(jì)描述
下一步就是通過describe屬性,對數(shù)據(jù)的統(tǒng)計(jì)特性進(jìn)行描述:
print df.describe()
# OUTPUT
Abra Apayao Benguet Ifugao Kalinga
count 79.000000 79.000000 79.000000 79.000000 79.000000
mean 12874.379747 16860.645570 3237.392405 12414.620253 30446.417722
std 16746.466945 15448.153794 1588.536429 5034.282019 22245.707692
min 927.000000 401.000000 148.000000 1074.000000 2346.000000
25% 1524.000000 3435.500000 2328.000000 8205.000000 8601.500000
50% 5790.000000 10588.000000 3202.000000 13044.000000 24494.000000
75% 13330.500000 33289.000000 3918.500000 16099.500000 52510.500000
max 60303.000000 54625.000000 8813.000000 21031.000000 68663.000000
Python有一個(gè)很好的統(tǒng)計(jì)推斷包。那就是scipy里面的stats。ttest_1samp實(shí)現(xiàn)了單樣本t檢驗(yàn)。因此,如果我們想檢驗(yàn)數(shù)據(jù)Abra列的稻谷產(chǎn)量均值,通過零假設(shè),這里我們假定總體稻谷產(chǎn)量均值為15000,我們有:
from scipy import stats as ss
# Perform one sample t-test using 1500 as the true mean
print ss.ttest_1samp(a = df.ix[:, 'Abra'], popmean = 15000)
# OUTPUT
(-1.1281738488299586, 0.26270472069109496)
返回下述值組成的元祖:
t : 浮點(diǎn)或數(shù)組類型
t統(tǒng)計(jì)量
prob : 浮點(diǎn)或數(shù)組類型
two-tailed p-value 雙側(cè)概率值
通過上面的輸出,看到p值是0.267遠(yuǎn)大于α等于0.05,因此沒有充分的證據(jù)說平均稻谷產(chǎn)量不是150000。將這個(gè)檢驗(yàn)應(yīng)用到所有的變量,同樣假設(shè)均值為15000,我們有:
print ss.ttest_1samp(a = df, popmean = 15000)
# OUTPUT
(array([ -1.12817385, 1.07053437, -65.81425599, -4.564575 , 6.17156198]),
array([ 2.62704721e-01, 2.87680340e-01, 4.15643528e-70,
1.83764399e-05, 2.82461897e-08]))
第一個(gè)數(shù)組是t統(tǒng)計(jì)量,第二個(gè)數(shù)組則是相應(yīng)的p值。
可視化
Python中有許多可視化模塊,最流行的當(dāng)屬matpalotlib庫。稍加提及,我們也可選擇bokeh和seaborn模塊。之前的博文中,我已經(jīng)說明了matplotlib庫中的盒須圖模塊功能。
# Import the module for plotting
import matplotlib.pyplot as plt
plt.show(df.plot(kind = 'box'))
現(xiàn)在,我們可以用pandas模塊中集成R的ggplot主題來美化圖表。要使用ggplot,我們只需要在上述代碼中多加一行,
import matplotlib.pyplot as plt
pd.options.display.mpl_style = 'default' # Sets the plotting display theme to ggplot2
df.plot(kind = 'box')
這樣我們就得到如下圖表:
比matplotlib.pyplot主題簡潔太多。但是在本博文中,我更愿意引入seaborn模塊,該模塊是一個(gè)統(tǒng)計(jì)數(shù)據(jù)可視化庫。因此我們有:
# Import the seaborn library
import seaborn as sns
# Do the boxplot
plt.show(sns.boxplot(df, widths = 0.5, color = "pastel"))
多性感的盒式圖,繼續(xù)往下看。
plt.show(sns.violinplot(df, widths = 0.5, color = "pastel"))
plt.show(sns.distplot(df.ix[:,2], rug = True, bins = 15))
with sns.axes_style("white"):
plt.show(sns.jointplot(df.ix[:,1], df.ix[:,2], kind = "kde"))
plt.show(sns.lmplot("Benguet", "Ifugao", df))
創(chuàng)建自定義函數(shù)
Python中,我們使用def函數(shù)來實(shí)現(xiàn)一個(gè)自定義函數(shù)。例如,如果我們要定義一個(gè)兩數(shù)相加的函數(shù),如下即可:
def add_2int(x, y):
return x + y
print add_2int(2, 2)
# OUTPUT
順便說一下,Python中的縮進(jìn)是很重要的。通過縮進(jìn)來定義函數(shù)作用域,就像在R語言中使用大括號{…}一樣。這有一個(gè)我們之前博文的例子:
產(chǎn)生10個(gè)正態(tài)分布樣本,其中u=3和o.
基于95%的置信度,計(jì)算 x_bar 和 x_bar2 ;
重復(fù)100次; 然后
計(jì)算出置信區(qū)間包含真實(shí)均值的百分比
Python中,程序如下:
import numpy as np
import scipy.stats as ss
def case(n = 10, mu = 3, sigma = np.sqrt(5), p = 0.025, rep = 100):
m = np.zeros((rep, 4))
for i in range(rep):
norm = np.random.normal(loc = mu, scale = sigma, size = n)
xbar = np.mean(norm)
low = xbar - ss.norm.ppf(q = 1 - p) * (sigma / np.sqrt(n))
up = xbar + ss.norm.ppf(q = 1 - p) * (sigma / np.sqrt(n))
if (mu > low) & (mu < up):
rem = 1
else:
rem = 0
m[i, :] = [xbar, low, up, rem]
inside = np.sum(m[:, 3])
per = inside / rep
desc = "There are " + str(inside) + " confidence intervals that contain "
"the true mean (" + str(mu) + "), that is " + str(per) + " percent of the total CIs"
return {"Matrix": m, "Decision": desc}
上述代碼讀起來很簡單,但是循環(huán)的時(shí)候就很慢了。下面針對上述代碼進(jìn)行了改進(jìn),這多虧了Python專家。
import numpy as np
import scipy.stats as ss
def case2(n = 10, mu = 3, sigma = np.sqrt(5), p = 0.025, rep = 100):
scaled_crit = ss.norm.ppf(q = 1 - p) * (sigma / np.sqrt(n))
norm = np.random.normal(loc = mu, scale = sigma, size = (rep, n))
xbar = norm.mean(1)
low = xbar - scaled_crit
up = xbar + scaled_crit
rem = (mu > low) & (mu < up)
m = np.c_[xbar, low, up, rem]
inside = np.sum(m[:, 3])
per = inside / rep
desc = "There are " + str(inside) + " confidence intervals that contain "
"the true mean (" + str(mu) + "), that is " + str(per) + " percent of the total CIs"
return {"Matrix": m, "Decision": desc}
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
LSTM 模型輸入長度選擇技巧:提升序列建模效能的關(guān)鍵? 在循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)家族中,長短期記憶網(wǎng)絡(luò)(LSTM)憑借其解決長序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報(bào)考條件詳解與準(zhǔn)備指南? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代浪潮下,CDA 數(shù)據(jù)分析師認(rèn)證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計(jì)的實(shí)用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強(qiáng)大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實(shí)施重大更新。 此次更新旨在確保認(rèn) ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務(wù)的價(jià)值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡稱 BI)深度融合的時(shí)代,BI ...
2025-07-10SQL 在預(yù)測分析中的應(yīng)用:從數(shù)據(jù)查詢到趨勢預(yù)判? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代,預(yù)測分析作為挖掘數(shù)據(jù)潛在價(jià)值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結(jié)束后:分析師的收尾工作與價(jià)值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結(jié)束)并非工作的終點(diǎn),而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報(bào)考到取證的全攻略? 在數(shù)字經(jīng)濟(jì)蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢性檢驗(yàn):捕捉數(shù)據(jù)背后的時(shí)間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢性檢驗(yàn)如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時(shí)間維度的精準(zhǔn)切片? ? 在數(shù)據(jù)的世界里,時(shí)間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準(zhǔn) ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應(yīng)用與實(shí)戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認(rèn)證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗(yàn):數(shù)據(jù)趨勢與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領(lǐng)域中,準(zhǔn)確捕捉數(shù)據(jù)的趨勢變化以及識別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認(rèn)證作為國內(nèi)權(quán)威的數(shù)據(jù)分析能力認(rèn)證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應(yīng)對策略? 長短期記憶網(wǎng)絡(luò)(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的一種變體,憑借獨(dú)特的門控機(jī)制,在 ...
2025-07-07統(tǒng)計(jì)學(xué)方法在市場調(diào)研數(shù)據(jù)中的深度應(yīng)用? 市場調(diào)研是企業(yè)洞察市場動(dòng)態(tài)、了解消費(fèi)者需求的重要途徑,而統(tǒng)計(jì)學(xué)方法則是市場調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書考試全攻略? 在數(shù)字化浪潮席卷全球的當(dāng)下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動(dòng)力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關(guān)鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準(zhǔn)確性的基礎(chǔ) ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動(dòng)力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價(jià)值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03