python导入外部数据(python如何导入数据库)
python中如何将表中的数据做成一张表,然后再从中取出数据?
第一部分是生成数据表,常见的生成方法有两种,第一种是导入外部数据,第二种是直接写入数据。 Excel 中的文件菜单中提供了获取外部数据的功能,支持数据库和文本文件和页面的多种数据源导入。
获取外部数据
python 支持从多种类型的数据导入。在开始使用 python 进行数据导入前需要先导入 pandas 库,为了方便起见,我们也同时导入 numpy 库。
1 import numpy as np
2 import pandas as pd
导入数据表
下面分别是从 excel 和 csv 格式文件导入数据并创建数据表的方法。代码是最简模式,里面有很多可选参数设置,例如列名称,索引列,数据格式等等。感兴趣的朋友可以参考 pandas 的
官方文档。
1 df=pd.DataFrame(pd.read_csv(‘name.csv’,header=1))
2 df=pd.DataFrame(pd.read_excel(‘name.xlsx’))
创建数据表
另一种方法是通过直接写入数据来生成数据表,excel 中直接在单元格中输入数据就可以,python 中通过下面的代码来实现。生成数据表的函数是 pandas 库中的 DateFrame 函数,数据表一共有 6 行数据,每行有 6 个字段。在数据中我们特意设置了一些 NA 值和有问题的字段,例如包含空格等。后面将在数据清洗步骤进行处理。后面我们将统一以 DataFrame 的简称 df 来命名数据表。
1 df = pd.DataFrame({‘id’:[1001,1002,1003,1004,1005,1006],
2 ‘date’:pd.date_range(‘20130102’, periods=6),
3 ‘city’:['Beijing ', ‘SH’, ’ guangzhou ', ‘Shenzhen’, ‘shanghai’, 'BEIJING '],
4 ‘age’:[23,44,54,32,34,32],
5 ‘category’:[‘100-A’,‘100-B’,‘110-A’,‘110-C’,‘210-A’,‘130-F’],
6 ‘price’:[1200,np.nan,2133,5433,np.nan,4432]},
7 columns =[‘id’,‘date’,‘city’,‘category’,‘age’,‘price’])
这是刚刚创建的数据表,我们没有设置索引列,price 字段中包含有 NA 值,city 字段中还包含了一些脏数据。
数据表检查
python 中处理的数据量通常会比较大,所以就需要我们对数据表进行检查。比如我们之前的文章中介绍的纽约出租车数据和 Citibike 的骑行数据,数据量都在千万级,我们无法一目了然的了解数据表的整体情况,必须要通过一些方法来获得数据表的关键信息。数据表检查的另一个目的是了解数据的概况,例如整个数据表的大小,所占空间,数据格式,是否有空值和重复项和具体的数据内容。为后面的清洗和预处理做好准备。
数据维度(行列)
Excel 中可以通过 CTRL 向下的光标键,和 CTRL 向右的光标键来查看行号和列号。Python 中使用 shape 函数来查看数据表的维度,也就是行数和列数,函数返回的结果(6,6)表示数据表有 6 行,6 列。下面是具体的代码。
1 #查看数据表的维度
2 df.shape
3 (6, 6)
数据表信息
使用 info 函数查看数据表的整体信息,这里返回的信息比较多,包括数据维度,列名称,数据格式和所占空间等信息。
1 #数据表信息
2 df.info()
4 class ‘pandas.core.frame.DataFrame’
5 RangeIndex: 6 entries, 0 to 5
6 Data columns (total 6 columns):
7 id 6 non-null int64
8 date 6 non-null datetime64[ns]
9 city 6 non-null object
10 category 6 non-null object
11 age 6 non-null int64
12 price 4 non-null float64
13 dtypes: datetime64ns, float64(1), int64(2), object(2)
14 memory usage: 368.0 bytes
查看数据格式
Excel 中通过选中单元格并查看开始菜单中的数值类型来判断数据的格式。Python 中使用 dtypes 函数来返回数据格式。
Dtypes 是一个查看数据格式的函数,可以一次性查看数据表中所有数据的格式,也可以指定一列来单独查看。
1#查看数据表各列格式
2df.dtypes
3
4id int64
5date datetime64[ns]
6city object
7category object
8age int64
9price float64
10dtype: object
11
12#查看单列格式
13df[‘B’].dtype
14
15dtype(‘int64’)
查看空值
Excel 中查看空值的方法是使用“定位条件”功能对数据表中的空值进行定位。“定位条件”在“开始”目录下的“查找和选择”目录中。
Isnull 是 Python 中检验空值的函数,返回的结果是逻辑值,包含空值返回 True,不包含则返回 False。可以对整个数据表进行检查,也可以单独对某一列进行空值检查。
df_isnull
1#检查特定列空值
2df[‘price’].isnull()
3
40 False
51 True
62 False
73 False
84 True
95 False
10Name: price, dtype: bool
查看唯一值
Excel 中查看唯一值的方法是使用“条件格式”对唯一值进行颜色标记。Python 中使用 unique 函数查看唯一值。
Unique 是查看唯一值的函数,只能对数据表中的特定列进行检查。下面是代码,返回的结果是该列中的唯一值。类似与 Excel 中删除重复项后的结果。
1 #查看 city 列中的唯一值
2 df[‘city’].unique()34array(['Beijing ', ‘SH’, ’ guangzhou ', ‘Shenzhen’, ‘shanghai’, 'BEIJING '], dtype=object)
查看数据表数值
Python 中的 Values 函数用来查看数据表中的数值。以数组的形式返回,不包含表头信息。
1#查看数据表的值
2df.values
3
4array([[1001, Timestamp(‘2013-01-02 00:00:00’), 'Beijing ', ‘100-A’, 23,
5 1200.0],
6 [1002, Timestamp(‘2013-01-03 00:00:00’), ‘SH’, ‘100-B’, 44, nan],
7 [1003, Timestamp(‘2013-01-04 00:00:00’), ’ guangzhou ', ‘110-A’, 54,
8 2133.0],
9 [1004, Timestamp(‘2013-01-05 00:00:00’), ‘Shenzhen’, ‘110-C’, 32,
10 5433.0],
11 [1005, Timestamp(‘2013-01-06 00:00:00’), ‘shanghai’, ‘210-A’, 34,
12 nan],
13 [1006, Timestamp(‘2013-01-07 00:00:00’), 'BEIJING ', ‘130-F’, 32,
14 4432.0]], dtype=object)
查看列名称
Colums 函数用来单独查看数据表中的列名称。
1 #查看列名称
2 df.columns
3
4 Index([‘id’, ‘date’, ‘city’, ‘category’, ‘age’, ‘price’], dtype=‘object’)
查看前 10 行数据
Head 函数用来查看数据表中的前 N 行数据,默认 head()显示前 10 行数据,可以自己设置参数值来确定查看的行数。下面的代码中设置查看前 3 行的数据。
1#查看前 3 行数据``df.head(``3``)
Tail 行数与 head 函数相反,用来查看数据表中后 N 行的数据,默认 tail()显示后 10 行数据,可以自己设置参数值来确定查看的行数。下面的代码中设置查看后 3 行的数据。
1#查看最后 3 行df.tail(3)
数据分析员用python做数据分析是怎么回事,需要用到python中的那些内容,具体是怎么操作的?
最近,Analysis with Programming加入了Planet Python。我这里来分享一下如何通过Python来开始数据分析。具体内容如下:
数据导入
导入本地的或者web端的CSV文件;
数据变换;
数据统计描述;
假设检验
单样本t检验;
可视化;
创建自定义函数。
数据导入
1
这是很关键的一步,为了后续的分析我们首先需要导入数据。通常来说,数据是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 = ""
df = pd.read_csv(data_url)
为了读取本地CSV文件,我们需要pandas这个数据分析库中的相应模块。其中的read_csv函数能够读取本地和web数据。
END
数据变换
1
既然在工作空间有了数据,接下来就是数据变换。统计学家和科学家们通常会在这一步移除分析中的非必要数据。我们先看看数据(下图)
对R语言程序员来说,上述操作等价于通过print(head(df))来打印数据的前6行,以及通过print(tail(df))来打印数据的后6行。当然Python中,默认打印是5行,而R则是6行。因此R的代码head(df, n = 10),在Python中就是df.head(n = 10),打印数据尾部也是同样道理
2
在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')
3
数据转置使用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
Other transformations such as sort can be done using codesort/code attribute. Now let's extract a specific column. In Python, we do it using either codeiloc/code or codeix/code attributes, but codeix/code is more robust and thus I prefer it. Assuming we want the head of the first column of the data, we have
4
其他变换,例如排序就是用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
5
顺便提一下,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']]。
6
为了舍弃数据中的列,这里是列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,那么就舍弃行。
END
统计描述
1
下一步就是通过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
END
假设检验
1
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 双侧概率值
2
通过上面的输出,看到p值是0.267远大于α等于0.05,因此没有充分的证据说平均稻谷产量不是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值
END
可视化
1
Python中有许多可视化模块,最流行的当属matpalotlib库。稍加提及,我们也可选择bokeh和seaborn模块。之前的博文中,我已经说明了matplotlib库中的盒须图模块功能。
2
# Import the module for plotting
import matplotlib.pyplot as plt
plt.show(df.plot(kind = 'box'))
现在,我们可以用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')
3
这样我们就得到如下图表:
4
比matplotlib.pyplot主题简洁太多。但是在本文中,我更愿意引入seaborn模块,该模块是一个统计数据可视化库。因此我们有:
# Import the seaborn library
import seaborn as sns
# Do the boxplot
plt.show(sns.boxplot(df, widths = 0.5, color = "pastel"))
5
多性感的盒式图,继续往下看。
6
plt.show(sns.violinplot(df, widths = 0.5, color = "pastel"))
7
plt.show(sns.distplot(df.ix[:,2], rug = True, bins = 15))
8
with sns.axes_style("white"):
plt.show(sns.jointplot(df.ix[:,1], df.ix[:,2], kind = "kde"))
9
plt.show(sns.lmplot("Benguet", "Ifugao", df))
END
创建自定义函数
在Python中,我们使用def函数来实现一个自定义函数。例如,如果我们要定义一个两数相加的函数,如下即可:
def add_2int(x, y):
return x + y
print add_2int(2, 2)
# OUTPUT
4
顺便说一下,Python中的缩进是很重要的。通过缩进来定义函数作用域,就像在R语言中使用大括号{…}一样。这有一个我们之前博文的例子:
产生10个正态分布样本,其中和
基于95%的置信度,计算和?;
重复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 sklearn 怎么导入外部数据进行训练
写入excel表时有两种写入xls和csv,但建议少使用csv,不然在表中调整数据格式时,保存时一直询问你是否保存新格式,很麻烦。
而在读取数据时,如果指定了哪一张sheet,则在pycharm又会出现格式不对齐。
还有将数据写入表格中时,excel会自动给你在表格最前面增加一个字段,对数据行进行编号。