Python運用於資料分析的簡單教程
最近,Analysis with Programming加入了Planet Python。作為該網站的首批特約博客,我在這裡來分享如何透過Python來開始數據分析。內容內容如下:
資料匯入
導入本地或web端的CSV檔案;
資料轉換; 視覺化;
建立自訂函數。
這是很關鍵的一步,為了後續的分析我們首先需要導入資料。通常來說,資料是CSV格式,就算不是,至少也可以轉換成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這個資料分析庫中的對應模組。其中的read_csv函數能夠讀取本機和web資料。
數據變換
既然在工作空間有了數據,接下來就是數據變換。統計學家和科學家通常會在這一步驟移除分析中的非必要數據。我們先來看看數據:
# 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語言程式設計師來說,上述操作等價於透過print(head(df))來列印資料的前6行,以及透過print(tail(df))來列印數據的後6行。當然Python中,預設列印是5行,而R則是6行。因此R的程式碼head(df, n = 10),在Python中就是df.head(n = 10),列印資料尾部也是同樣道理。
在R語言中,資料列和行的名字透過colnames和rownames來分別進行擷取。在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')
資料轉置使用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屬性。現在我們提取特定的某列資料。 Python中,可以使用iloc或ix屬性。但我比較喜歡用ix,因為它比較穩定一些。假設我們需資料第一列的前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列數據,我們有:
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
上述指令相當於df.ix[10:20, ['Abra', 'Apayao', 'Benguet']]。
為了捨棄資料中的列,這裡是列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 參數告訴函數到底捨棄列還是行。如果axis等於0,那麼就捨棄行。
統計描述
下一步就是透過describe屬性,對資料的統計特性進行描述:
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有一個很好的統計推斷套件。那就是scipy裡面的stats。 ttest_1samp實現了單樣本t檢定。因此,如果我們想檢定資料Abra列的稻穀產量平均值,透過零假設,這裡我們假定總體稻穀產量平均值為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 : 浮點或陣列類型
t統計量prob : 浮點或陣列類型
two-tailed p-value 雙側機率值
透過上面的輸出,看到p值是0.267遠大於α稻穀產量不是150000。將此檢定應用到所有的變量,同樣假設均值為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]))
第一個數組是t統計量,第二個數組則是對應的p值。 可視化Python中有許多可視化模組,最流行的當屬matpalotlib庫。稍加提及,我們也可選擇bokeh和seaborn模組。在之前的部落格文章中,我已經說明了matplotlib庫中的盒須圖模組功能。
# Import the module for plotting import matplotlib.pyplot as plt plt.show(df.plot(kind = 'box'))
import matplotlib.pyplot as plt pd.options.display.mpl_style = 'default' # Sets the plotting display theme to ggplot2 df.plot(kind = 'box')

# Import the seaborn library import seaborn as sns # Do the boxplot plt.show(sns.boxplot(df, widths = 0.5, color = "pastel"))
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))
创建自定义函数
在Python中,我们使用def函数来实现一个自定义函数。例如,如果我们要定义一个两数相加的函数,如下即可:
def add_2int(x, y): return x + y print add_2int(2, 2) # OUTPUT 4
顺便说一下,Python中的缩进是很重要的。通过缩进来定义函数作用域,就像在R语言中使用大括号{…}一样。这有一个我们之前博文的例子:
产生10个正态分布样本,其中u=3和o.
基于95%的置信度,计算 x_bar 和 x_bar2 ;
重复100次; 然后
计算出置信区间包含真实均值的百分比
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}
上述代码读起来很简单,但是循环的时候就很慢了。下面针对上述代码进行了改进,这多亏了 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}
更多Python運用於資料分析的簡單教程相关文章请关注PHP中文网!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。Python以简洁和强大的生态系统著称,C 则以高性能和底层控制能力闻名。

Python在遊戲和GUI開發中表現出色。 1)遊戲開發使用Pygame,提供繪圖、音頻等功能,適合創建2D遊戲。 2)GUI開發可選擇Tkinter或PyQt,Tkinter簡單易用,PyQt功能豐富,適合專業開發。

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

要在有限的時間內最大化學習Python的效率,可以使用Python的datetime、time和schedule模塊。 1.datetime模塊用於記錄和規劃學習時間。 2.time模塊幫助設置學習和休息時間。 3.schedule模塊自動化安排每週學習任務。

Python在開發效率上優於C ,但C 在執行性能上更高。 1.Python的簡潔語法和豐富庫提高開發效率。 2.C 的編譯型特性和硬件控制提升執行性能。選擇時需根據項目需求權衡開發速度與執行效率。

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

每天學習Python兩個小時是否足夠?這取決於你的目標和學習方法。 1)制定清晰的學習計劃,2)選擇合適的學習資源和方法,3)動手實踐和復習鞏固,可以在這段時間內逐步掌握Python的基本知識和高級功能。
