转载自品略图书馆  http://www.pinlue.com/article/2019/03/2601/068413323231.html

Pandas是Python的一个大数据处理模块。Pandas使用一个二维的数据结构DataFrame来表示表格式的数据,相比较于Numpy,Pandas可以存储混合的数据结构,同时使用NaN来表示缺失的数据,而不用像Numpy一样要手工处理缺失的数据,并且Pandas使用轴标签来表示行和列。

DataFrame类:

DataFrame有四个重要的属性:

index:行索引。

columns:列索引。

values:值的二维数组。

name:名字。

构建方法,DataFrame(sequence),通过序列构建,序列中的每个元素是一个字典。

frame=DateFrame构建完之后,假设frame中有’name’,’age’,’addr’三个属性,可以使用fame["name’]查看属性列内容,也可以fame.name这样直接查看。

frame按照’属性提取出来的每个列是一个Series类。

DataFrame类可以使用布尔型索引。

groupby(str|array…)函数:可以使用frame中对应属性的str或者和frame行数相同的array作为参数还可以使用一个会返回和frame长度相同list的函数作为参数,如果使用函数做分组参数,这个用做分组的函数传入的参数将会是fame的index,参数个数任意。使用了groupby函数之后配合,size()函数就可以对groupby结果进行统计。

groupby后可以使用:

size():就是count

sum():分组求和

apply(func,axis=0):在分组上单独使用函数func返回frame,不groupby用在DataFrame会默认将func用在每个列上,如果axis=1表示将func用在行上。

reindex(index,column,method):用来重新命名索引,和插值。

size():会返回一个frame,这个frame是groupby后的结果。

sum(n).argsort():如果frame中的值是数字,可以使用sum函数计算frame中摸个属性,各个因子分别求和,并返回一个Series,这个Series可以做为frame.take的参数,拿到frame中对应的行。

pivot_table(操作str1,index=str2,columns=str3,aggfunc=str4)透视图函数:

str1:是给函数str4作为参数的部分。

str2:是返回frame的行名。

str3:是返回frame的列名。

str4:是集合函数名,有’mean’,’sum’这些,按照str2,str3分组。

使用透视图函数之后,可以使用.sum()这类型函数,使用后会按照index和columns的分组求和。

order_index(by,ascending):

返回一个根据by排序,asceding=True表示升序,False表示降序的frame

concat(list):将一个列表的frame行数加起来。

ix[index]:就是行索引,DataFrame的普通下标是列索引。

take(index):作用和ix差不多,都是查询行,但是ix传入行号,take传入行索引。

unstack():将行信息变成列信息。

apply(func,axis=0)和applymap(func):apply用在DataFrame会默认将func用在每个列上,如果axis=1表示将func用在行上。applymap表示func用在每个元素上。

combine_first(frame2):combine_first会把frame中的空值用frame1中对应位置的数据进行填充。Series方法也有相同的方法。

stack()函数,可以将DataFrame的列转化成行,原来的列索引成为行的层次索引。(stack和unstack方法是两个互逆的方法,可以用来进行Series和DataFrame之间的转换)

duplicated():返回一个布尔型Series,表示各行是否重复。

drop_duplicates():返回一个移除了重复行后的DataFrame

pct_change():Series也有这个函数,这个函数用来计算同colnums两个相邻的数字之间的变化率。

corr():计算相关系数矩阵。

cov():计算协方差系数矩阵。

corrwith(Series|list,axis=0):axis=0时计算frame的每列和参数的相关系数。

数据框操作

df.head(1) 读取头几条数据

df.tail(1) 读取后几条数据

df["date’] 获取数据框的date列

df.head(1)["date’] 获取第一行的date列

df.head(1)["date’][0] 获取第一行的date列的元素值

sum(df["ability’]) 计算整个列的和

df[df["date’] == "20161111’] 获取符合这个条件的行

df[df["date’] == "20161111’].index[0] 获取符合这个条件的行的行索引的值

df.iloc[1] 获取第二行

df.iloc[1]["test2’] 获取第二行的test2值

10 mins to pandas

df.index 获取行的索引

df.index[0] 获取第一个行索引

df.index[-1] 获取最后一个行索引,只是获取索引值

df.columns 获取列标签

df[0:2] 获取第1到第2行,从0开始,不包含末端

df.loc[1] 获取第二行

df.loc[:,’test1’] 获取test1的那一列,这个冒号的意思是所有行,逗号表示行与列的区分

df.loc[:,["test1’,’test2’]] 获取test1列和test2列的数据

df.loc[1,["test1’,’test2’]] 获取第二行的test1和test2列的数据

df.at[1,’test1’] 表示取第二行,test1列的数据,和上面的方法类似

df.iloc[0] 获取第一行

df.iloc[0:2,0:2] 获取前两行前两列的数据

df.iloc[[1,2,4],[0,2]] 获取第1,2,4行中的0,2列的数据

(df[2] > 1).any() 对于Series应用any()方法来判断是否有符合条件的

常用操作及结果

1、文件读取

首先将用到的pandas和numpy加载进来

import pandas as pd

import numpy as np

读取数据:

#csv和xlsx分别用read_csv和read_xlsx,下面以csv为例df=pd.read_csv("f:\1024.csv") 1

2

2、查看数据

df.head() ​#默认出5行,​括号里可以填其他数据1

2

3

3、查看数据类型

df.dtypes1

4、利用现有数据生成一列新数据

比如:max_time和min_time是现有的两列,现在业务需要生成一列gs,gs=max_time-min_time

df.["gs’]=df.["max_time’]-["min_time’]

#查看是否成功​df.head()1

2

3

5、查看基本统计量

df.describe(include="all") # all代表需要将所有列都列出1

2

通常来说,数据是CSV格式,就算不是,至少也可以转换成CSV格式。在Python中,我们的操作如下:

import pandas as pd# Reading data locallydf = pd.read_csv("/Users/al-ahmadgaidasaad/Documents/d.csv")# Reading data from webdata_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)1

2

3

4

5

6

7

8

9

为了读取本地CSV文件,我们需要pandas这个数据分析库中的相应模块。

其中的read_csv函数能够读取本地和web数据。

# Head of the dataprint df.head()# OUTPUT Abra ApayaoBenguet Ifugao Kalinga0 1243 2934 148 3300 105531 4158 9235 4287 8063 352572 1787 1922 1955 1074 45443 17152 14501 3536 19607 316874 1266 2385 2530 3315 8520# Tail of the dataprint df.tail()# OUTPUT Abra Apayao Benguet Ifugao Kalinga74 2505 20878 3519 19737 1651375 60303 40065 7062 19422 6180876 6311 6756 3561 15910 2334977 13345 38902 2583 11096 6866378 2623 18264 3745 16787 169001

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

上述操作等价于通过print(head(df))来打印数据的前6行,以及通过print(tail(df))来打印数据的后6行。

当然Python中,默认打印是5行,而R则是6行。因此R的代码head(df, n = 10),

在Python中就是df.head(n = 10),打印数据尾部也是同样道理。

在Python中,我们则使用columns和index属性来提取,如下:

# Extracting column namesprint df.columns# OUTPUTIndex([u"Abra", u"Apayao", u"Benguet", u"Ifugao", u"Kalinga"], dtype="object")# Extracting row names or the indexprint df.index# OUTPUTInt64Index([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], dtype="int64")1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

数据转置使用T方法,

# Transpose dataprint 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 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

其他变换,例如排序就是用sort属性。现在我们提取特定的某列数据。

Python中,可以使用iloc或者ix属性。但是我更喜欢用ix,因为它更稳定一些。假设我们需数据第一列的前5行,我们有:

print df.ix[:, 0].head()# OUTPUT0 12431 41582 17873 171524 1266Name: Abra, dtype: int641

2

3

4

5

6

7

8

9

顺便提一下,Python的索引是从0开始而非1。为了取出从11到20行的前3列数据,我们有:

print df.ix[10:20, 0:3]# OUTPUT Abra Apayao Benguet10 981 1311 256011 27366 15093 303912 1100 1701 238213 7212 11001 108814 1048 1427 284715 25679 15661 294216 1055 2191 211917 5437 6461 73418 1029 1183 230219 23710 12222 259820 1091 2343 26541

2

3

4

5

6

7

8

9

10

11

12

13

14

15

上述命令相当于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 Kalinga0 1243 3300 105531 4158 8063 352572 1787 1074 45443 17152 19607 316874 1266 3315 85201

2

3

4

5

6

7

8

9

axis 参数告诉函数到底舍弃列还是行。如果axis等于0,那么就舍弃行。

统计描述

下一步就是通过describe属性,对数据的统计特性进行描述:

print df.describe()# OUTPUT Abra Apayao Benguet Ifugao Kalingacount 79.000000 79.000000 79.000000 79.000000 79.000000mean 12874.379747 16860.645570 3237.392405 12414.620253 30446.417722std 16746.466945 15448.153794 1588.536429 5034.282019 22245.707692min 927.000000 401.000000 148.000000 1074.000000 2346.00000025% 1524.000000 3435.500000 2328.000000 8205.000000 8601.50000050% 5790.000000 10588.000000 3202.000000 13044.000000 24494.00000075% 13330.500000 33289.000000 3918.500000 16099.500000 52510.500000max 60303.000000 54625.000000 8813.000000 21031.000000 68663.0000001

2

3

4

5

6

7

8

9

10

11

12

Python有一个很好的统计推断包。那就是scipy里面的stats。ttest_1samp实现了单样本t检验。因此,如果我们想检验数据Abra列的稻谷产量均值,通过零假设,这里我们假定总体稻谷产量均值为15000,我们有:

from scipy import stats as ss# Perform one sample t-test using 1500 as the true meanprint ss.ttest_1samp(a = df.ix[:, "Abra"], popmean = 15000)# OUTPUT(-1.1281738488299586, 0.26270472069109496)1

2

3

4

5

6

7

返回下述值组成的元祖:

t : 浮点或数组类型

t统计量

prob : 浮点或数组类型

two-tailed p-value 双侧概率值

通过上面的输出,看到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]))1

2

3

4

5

6

7

第一个数组是t统计量,第二个数组则是相应的p值。

可视化

Python中有许多可视化模块,最流行的当属matpalotlib库。稍加提及,我们也可选择bokeh和seaborn模块。之前的博文中,我已经说明了matplotlib库中的盒须图模块功能。

# Import the module for plottingimport matplotlib.pyplot as pltplt.show(df.plot(kind = "box"))1

2

3

现在,我们可以用pandas模块中集成R的ggplot主题来美化图表。要使用ggplot,我们只需要在上述代码中多加一行,

import matplotlib.pyplot as pltpd.options.display.mpl_style = "default" # Sets the plotting display theme to ggplot2df.plot(kind = "box")# Import the seaborn libraryimport seaborn as sns# Do the boxplotplt.show(sns.boxplot(df, widths = 0.5, color = "pastel"))import numpy as npimport scipy.stats as ssdef 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}import numpy as npimport scipy.stats as ssdef 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}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

读取数据

Pandas使用函数read_csv()来读取csv文件

import pandasfood_info = ("food_info.csv")print(type(food_info))# 输出:<class "pandas.core.frame.DataFrame"> 可见读取后变成一个DataFrame变量1

2

3

4

5

使用函数head( m )来读取前m条数据,如果没有参数m,默认读取前五条数据

first_rows = food_info.head()first_rows = food_info.head(3)1

2

3

print(food_info.columns)# 输出:输出全部的列名,而不是用省略号代替Index(["NDB_No", "Shrt_Desc", "Water_(g)", "Energ_Kcal", "Protein_(g)", "Lipid_Tot_(g)", "Ash_(g)", "Carbohydrt_(g)", "Fiber_TD_(g)", "Sugar_Tot_(g)", "Calcium_(mg)", "Iron_(mg)", "Magnesium_(mg)", "Phosphorus_(mg)", "Potassium_(mg)", "Sodium_(mg)", "Zinc_(mg)", "Copper_(mg)", "Manganese_(mg)", "Selenium_(mcg)", "Vit_C_(mg)", "Thiamin_(mg)", "Riboflavin_(mg)", "Niacin_(mg)", "Vit_B6_(mg)", "Vit_B12_(mcg)", "Vit_A_IU", "Vit_A_RAE", "Vit_E_(mg)", "Vit_D_mcg", "Vit_D_IU", "Vit_K_(mcg)", "FA_Sat_(g)", "FA_Mono_(g)", "FA_Poly_(g)", "Cholestrl_(mg)"], dtype="object")1

2

3

可以使用tolist()函数转化为list

food_info.columns.tolist()

与Numpy一样,用shape属性来显示数据的格式

dimensions = food_info.shapeprint(dimensions)print(dimensions)1

2

输出:(8618,36) ,

其中dimensions[0]为8618,dimensions[1]为36

与Numpy一样,用dtype属性来显示数据类型,Pandas主要有以下几种dtype:

object – 代表了字符串类型

int – 代表了整型

float – 代表了浮点数类型

datetime – 代表了时间类型

bool – 代表了布尔类型

索引

读取了文件后,Pandas会把文件的一行作为列的索引标签,使用行数字作为行的索引标签

注意,行标签是从数字0开始的

Pandas使用Series数据结构来表示一行或一列的数据,类似于Numpy使用向量来表示数据。Numpy只能使用数字来索引,而Series可以使用非数字来索引数据,当你选择返回一行数据的时候,Series并不仅仅返回该行的数据,同时还有每一列的标签的名字。

python之panda模块理解与学习。相关推荐

  1. python的os模块使用_Python学习笔记之os模块使用总结

    #!/usr/bin/env python ##-*- coding: utf-8 -*- import os print "n欢迎大家跟我一起学Python"; system=o ...

  2. python之panda模块1

    Python是一门实现数据可视化很好的语言,他们里面的很多库可以很好的画出图形,形象明了. 今天我们就来说说:Pandas数据分析核心支持库 初识Pandas: Pandas 是 Python 语言的 ...

  3. python rpa_(RPA学习)Python 之 Pathlib 模块

    原标题:(RPA学习)Python 之 Pathlib 模块 艺赛旗 RPA9.0全新首发免费下载 点击下载 http://www.i-search.com.cn/index.html?from=li ...

  4. Python中Tkinter模块的Canvas控件使用学习(2:绘制简单工程符号)

      之前学习HTML5中Canvas绘图方法时,为测试函数功能,使用JavaScript在Canvas中绘制了多种工程图符号,下面两张图是工程图符号的原图.本文参照JavaScript绘图程序,使用p ...

  5. Python模块EasyGui专题学习

    Python模块EasyGui专题学习 1.msgbox(msg,title,ok_button="OK",image="",root=None) 代码 imp ...

  6. python中socket模块常用吗_python网络学习笔记——socket模块使用记录

    此文章记录了笔者学习python网络中socket模块的笔记. 建议初次学习socket的读者先读一遍socket模块主要函数的介绍. socket模块的介绍可以参考笔者的前一篇关于socket官方文 ...

  7. python random模块导入_Python学习笔记(二十)—模块的导入

    一.模块介绍 Python 提供了强大的模块支持,主要体现在Python 标准库中包含了大量的模块(称为标准模块),还有大量的第三方模块,开发者自己也可以开发自定义模块.通过这些强大的模块可以极大地提 ...

  8. python中confIgparser模块学习

    python中configparser模块学习 ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section ...

  9. python 彩票排列组合_对福彩3D号码进行排列组合为例学习Python的itertools模块的用法...

    这里我们以对福彩3D号码进行排列组合为例学习Python的itertools模块的用法.首先我们选择心仪的号码.比如我们选择4,5,7,8 第一种我们只要组六的组合.代码如下 import itert ...

最新文章

  1. eclipse中java项目转换为web项目
  2. statpot:使用mongo+bootstrap+highcharts做统计报表
  3. Java动态代理类使用
  4. Code Complete
  5. kubernetes mysql ip_弄明白kubernetes中的“三种IP”
  6. topshelf和quartz内部分享
  7. 读书和不读书有什么区别呢?
  8. VB用记录集填充表格函数
  9. [MAC] 6 个好用小技巧
  10. 帆软日期格式转换_FineReport帆软报表相关学习笔记,纪要
  11. 计算机c盘被保护怎么解开,电脑磁盘被写保护怎么办?总结几种去掉电脑磁盘写保护的方法...
  12. java游戏猿人时代_猿人时代游戏下载
  13. C语言---简单五子棋小游戏
  14. JS 之Node节点的 属性、方法 获取
  15. 斯坦福大学公开课机器学习:Neural Networks,representation: non-linear hypotheses(为什么需要做非线性分类器)...
  16. 外贸人必备的实用工具
  17. 『WEB』web学习
  18. 考研英语核心词汇梳理三
  19. 什么是PHP?它的擅长领域是什么?它的工作原理是什么?
  20. JS报错 Uncaught TypeError: undefined is not a function,解决

热门文章

  1. Rust随机数库rand rand_core rand_chacha等
  2. 机器学习线性回归——概念梳理及非线性拟合
  3. 盘点2018八大行业并购
  4. 私藏分享:关于企业架构中如何进行平台化
  5. (转)阿里巴巴大数据平台“达芬奇密码”进化论
  6. decawave1001-DEV简介开发环境搭建
  7. C++生成csv文件
  8. oracle缺省口令,更改口令加密的缺省算法(任务)
  9. 通达信交易接口函数Java接口抽象法
  10. PHP APP端支付宝支付