Python数据分析入门
原文:http://python.jobbole.com/81133/
本文由 伯乐在线 - Den 翻译,toolate 校稿。未经许可,禁止转载!
英文出处:alstatr.blogspot.ca。欢迎加入翻译组。
最近,Analysis with Programming加入了Planet Python。作为该网站的首批特约博客,我这里来分享一下如何通过Python来开始数据分析。具体内容如下:
- 数据导入
- 导入本地的或者web端的CSV文件;
 
- 数据变换;
- 数据统计描述;
- 假设检验
- 单样本t检验;
 
- 可视化;
- 创建自定义函数。
数据导入
这是很关键的一步,为了后续的分析我们首先需要导入数据。通常来说,数据是CSV格式,就算不是,至少也可以转换成CSV格式。在Python中,我们的操作如下:
| 1 2 3 4 5 6 7 8 | 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数据。
数据变换
既然在工作空间有了数据,接下来就是数据变换。统计学家和科学家们通常会在这一步移除分析中的非必要数据。我们先看看数据:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | # 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属性来提取,如下:
| 1 2 3 4 5 6 7 8 9 10 11 | # 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 | 
