上一篇讲了numpy,除此之外,还有一个工具我们一定会使用,那就是pandas。如果说numpy中数据存储形式是列表的话,那么pandas中数据的存储形式更像是字典。为什么这么说呢?因为pandas中的数据每一行每一列都有名字,而numpy中没有。本文主要介绍pandas的基本使用方法,更多高级用法大家可以参考 pandas官方文档

一、pandas的安装及导入

安装:命令行中输入以下代码

pip3 install pandas

导入:为了简便,这里使用pd作为pandas的缩写(因为pandas依赖numpy,所以在使用之前需要安装和导入numpy)

import numpy as np
import pandas as pd

二、新建pandas列表、矩阵及其属性

创建方法:

pd.Series:创建pandas列表

pd.date_range:创建pandas日期列表

pd.DataFrame:创建pandas矩阵

矩阵属性

dtypes:数据类型

index:行名

columns:列名

values:数据值

describe():实值数据列的统计数据

T:矩阵的倒置

sort_index(axis=, ascending=):矩阵排序{axis:0(行排序),1(列排序)}{ascending:True(升序),False(降序)}

sort_values(by=, ascending=):按某一列的值排序{by:列名}

s = pd.Series([1, 3, 6, np.nan, 23, 3])
dates = pd.date_range('20180708', periods=6)
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=['a', 'b', 'c', 'd'])
df2 = pd.DataFrame({
'a':pd.Series([1, 2, 3, 4]),
'b':pd.Timestamp('20180708'),
'c':pd.Categorical(['cate1', 'cate2', 'cate3', 'cate4'])
})
print(df2)
print(df2.dtypes)
print(df2.index)
print(df2.columns)
print(df2.values)
print(df2.describe())
print(df2.T)
print(df2.sort_index(axis=1, ascending=False))
print(df2.sort_index(axis=0, ascending=False))
print(df2.sort_values(by='a', ascending=False))

三、pandas选择数据

.列名:选择某一列

[列名]:选择某一列

[start : end]:选择行索引以start开头,end - 1结尾的数据

[行名start:行名end]:选择行名以start开头,end结尾的数据

loc[行名选择, 列名选择]:根据行名和列名选择数据

iloc[行索引选择, 列索引选择]:根据行索引和列索引选择数据

ix[行 名/索引 选择,列 名/索引 选择]:混合 名/索引 选择数据

[布尔表达式]:根据布尔表达式结果选择数据,只有当布尔表达式为真时的数据才会被选择

dates = pd.date_range('20180709', periods=3)
df = pd.DataFrame(np.arange(12).reshape((3, 4)), index=dates, columns=['A', 'B', 'C', 'D'])
print(df.A)
print(df['A'])
print(df[2:3])
print(df['20180709':'20180710']) # loc: select by label
print(df.loc['20180711'])
print(df.loc[:,['B','C']]) # iloc : select by position
print(df.iloc[1:3, 2:4])
print(df.iloc[[0, 2], 2:4]) # ix : mixed selection
print(df.ix[[0, 2], ['B']]) # Boolean indexing
print(df[df.A > 3])

四、pandas设置数据值

首先选择数据,然后直接通过赋值表达式,即可将选择的数据设置为相应的值

dates = pd.date_range('20180709', periods=3)
df = pd.DataFrame(np.arange(12).reshape((3, 4)), index=dates, columns=['A', 'B', 'C', 'D'])
df.loc['20180709', 'B'] = 666
df.iloc[2, 2] = 999
df.ix['20180709', 3] = 777
df.A[df.A > 3] = 888
df['F'] = np.nan
print(df)

五、pandas处理NaN值

dropna(axis=, how=):丢弃NaN数据,{axis:0(按行丢弃),1(按列丢弃)} {how:'any'(只要含有NaN数据就丢弃),'all'(所有数据都为NaN时丢弃)}

fillna(value=):将NaN值都设置为value的值

isnull():对每各元素进行判断是否是NaN,返回结果矩阵

np.any(matrix) == value:判断matrix矩阵中是否有value值

np.all(matrix) == value:判断matrix矩阵中是否所有元素都是value值

dates = pd.date_range('20180709', periods=5)
df = pd.DataFrame(np.arange(20).reshape((5, 4)), index=dates, columns=['A', 'B', 'C', 'D'])
df.iloc[3, 3] = np.nan
print(df.dropna(axis=1, how='all')) # how = {'any', 'all'}
print(df.fillna(value=666))
print(df.isnull())
print(np.any(df.isnull()) == True)
print(np.all(df.isnull()) == True)

六、pandas读取数据、导出数据

根据数据的格式,pandas提供了多种数据读取和导出的方法,如:

读取数据:read_csv、read_table、read_fwf、read_clipboard、read_excel、read_hdf

导出数据:to_csv、to_table、to_fwf、to_clipboard、to_excel、to_hdf

df = pd.read_csv('Q1.csv')
print(df)
df.to_csv('Q1_pandas.csv')

七、pandas合并数据

concat方法

第一个参数:需要合并的矩阵

axis:合并维度,0:按行合并,1:按列合并

join:处理非公有 列/行 的方式,inner:去除非公有的 列/行,outer:对非公有的 列/行 进行NaN值填充然后合并

ignore_index:是否重排行索引

df1 = pd.DataFrame(np.arange(12).reshape(3, 4), columns=['A', 'B', 'C', 'D'], index=[0, 1, 2])
df2 = pd.DataFrame(np.ones((3, 4)), columns=['B', 'C', 'D', 'E'], index=[1, 2, 3]) print(pd.concat([df1, df2], join='outer', ignore_index=True)) # join = {'outer', 'inner'}
print(pd.concat([df1, df2], axis=1, join_axes=[df1.index]))
print(df1.append([df2], ignore_index=True))

merge方法

第一个参数、第二个参数:需要合并的矩阵

on:公有列名

how:处理非公有行的方式,inner:去除非公有行,outer:对非公有的行进行NaN值填充然后合并,left:保留左矩阵的所有行,对非公有的元素进行NaN值填充,right:保留右边矩阵的所有行,对非公有的元素进行NaN值填充

indicator:是否显示每一行的merge方式

suffixes:非公有列的列名后缀

df1 = pd.DataFrame({
'key':['K1', 'K2', 'K3'],
'A':['A1', 'A2', 'A3'],
'B':['B1', 'B2', 'B3']
})
df2 = pd.DataFrame({
'key':['K1', 'K2', 'K3'],
'C':['C1', 'C2', 'C3'],
'D':['D1', 'D2', 'D3']
})
print(pd.merge(df1, df2, on='key'))
df3 = pd.DataFrame({
'key1':['K1', 'K1', 'K0'],
'key2':['K1', 'K0', 'K1'],
'col':[1, 2, 3]
})
df4 = pd.DataFrame({
'key1':['K0', 'K1', 'K0'],
'key2':['K1', 'K0', 'K0'],
'col':[6, 7, 8]
})
# how = {'inner', 'outer', 'left', 'right'}
print(pd.merge(df3, df4, on=['key1', 'key2'], how='right', suffixes=['_left', '_right'], indicator=True))

八、pandas数据可视化

pandas数据可视化依赖matplotlib库,所以在可视化数据之前应该先导入该库

import matplotlib.pyplot as plt

首先通过np.ramdom方法生成四列随机数据

然后通过cumsum对随机数据做累加

再通过scatter方法以其中两列为绿色点X, Y的值,另两列为蓝色点X, Y的值

最后使用plt.show()方法画图

data = pd.DataFrame(np.random.randn(1000, 4),
index=np.arange(1000),
columns=list("ABCD"))
data = data.cumsum()
# plot methods:
# 'bar', 'hist', 'box', 'kde', 'area', 'scatter', 'hexbin', 'pie'
ax = data.plot.scatter(x='A', y='B', color='blue', label='class 1')
data.plot.scatter(x='C', y='D', color='green', label='class 2', ax=ax)
plt.show()

pandas入门指南的更多相关文章

  1. Web API 入门指南 - 闲话安全

    Web API入门指南有些朋友回复问了些安全方面的问题,安全方面可以写的东西实在太多了,这里尽量围绕着Web API的安全性来展开,介绍一些安全的基本概念,常见安全隐患.相关的防御技巧以及Web AP ...

  2. Vue.js 入门指南之“前传”(含sublime text 3 配置)

    题记:关注Vue.js 很久了,但就是没有动手写过一行代码,今天准备入手,却发现自己比菜鸟还菜,于是四方寻找大牛指点,才终于找到了入门的“入门”,就算是“入门指南”的“前传”吧.此文献给跟我一样“白痴 ...

  3. yii2实战教程之新手入门指南-简单博客管理系统

    作者:白狼 出处:http://www.manks.top/document/easy_blog_manage_system.html 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文 ...

  4. 【翻译】Fluent NHibernate介绍和入门指南

    英文原文地址:https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started 翻译原文地址:http://www.cnblogs ...

  5. ASP.NET MVC 5 入门指南汇总

    经过前一段时间的翻译和编辑,我们陆续发出12篇ASP.NET MVC 5的入门文章.其中大部分翻译自ASP.NET MVC 5 官方教程,由于本系列文章言简意赅,篇幅适中,从一个web网站示例开始讲解 ...

  6. 一起学微软Power BI系列-官方文档-入门指南(1)Power BI初步介绍

    我们在前一篇文章微软新神器-Power BI,一个简单易用,还用得起的BI产品中,我们初步介绍了Power BI的基本知识.由于Power BI是去年开始微软新发布的一个产品,虽然已经可以企业级应用, ...

  7. 一起学微软Power BI系列-官方文档-入门指南(2)获取源数据

    我们在文章: 一起学微软Power BI系列-官方文档-入门指南(1)Power BI初步介绍中,我们介绍了官方入门文档的第一章.今天继续给大家介绍官方文档中,如何获取数据源的相关内容.虽然是英文,但 ...

  8. 一起学微软Power BI系列-官方文档-入门指南(3)Power BI建模

    我们前2篇文章:一起学微软Power BI系列-官方文档-入门指南(1)Power BI初步介绍 和一起学微软Power BI系列-官方文档-入门指南(2)获取源数据 中,我们介绍了官方入门文档与获取 ...

  9. 一起学微软Power BI系列-官方文档-入门指南(4)Power BI的可视化

    在前面的系列文章中,我们介绍了官方有关获取数据,以及建模的原始文档和基本介绍.今天继续给大家介绍官方文档中,有关可视化的内容.实际上获获取数据和建模更注重业务关系的处理,而可视化则关注对数据的解读.这 ...

随机推荐

  1. linux各种终端类型的区别和概念

    1 pty(虚拟终端或伪终端): 当我们远程telnet到主机或使用xterm时不也需要一个终端交互么?是的,这就是虚拟终端pty(pseudo-tty). 2 tty(终端设备的统称):tty一词源 ...

  2. centos7.2快速搭建LAMP平台

    #查看linux系统版本信息 cat /etc/redhat-release 以上是操作系统的所有信息,补充下内核信息参数介绍: 3.10.0-514.26.2.el7.x86_64 3表示主版本号, ...

  3. 【php】类型转换

    $a = 9; print_r((array) $a) ; 输出: [0=>9] print_r((array) null); 输出: []

  4. Python面向对象(类之间的关系)(三)

    类与类之间的关系 在我们的世界中事物和事物之间总会有一些联系. 在面向对象中. 类和类之间也可以产生相关的关系 1. 依赖关系 执行某个动作的时候. 需要xxx来帮助你完成这个操作. 此时的关系是最轻 ...

  5. WordPress 编辑器没有可视化

    第一次安装wordpress后出现文章编辑器只有一行按钮的问题,即使我安装了其他的编辑插件也是一样只有一行, 解决方法: 原来是再Users->All Users 中勾选了Disable the ...

  6. x86保护模式-七中断和异常

    x86保护模式-七中断和异常 386相比较之前的cpu   增强了中断处理能力   并且引入了 异常概念 一 80386的中断和异常 为了支持多任务和虚拟存储器等功能,386把外部中断称为中断     ...

  7. A Survey of Model Compression and Acceleration for Deep Neural Network时s

    A Survey of Model Compression and Acceleration for Deep Neural Network时s 本文全面概述了深度神经网络的压缩方法,主要可分为参数修 ...

  8. 2017 Multi-University Training Contest - Team 4

    日常绝望系列 Questionnaire HDU - 6075 In order to get better results in official ACM/ICPC contests, the te ...

  9. ubuntu系统下如何禁用笔记本触摸板

    命令行方式,得每次用终端输入命令行设置,不方便. sudo rmmod psmouse          # 用来禁用触摸板 sudo modprobe psmouse     # 用来启用触摸板 想 ...

  10. 84. Spring Boot集成MongoDB【从零开始学Spring Boot】

    至于MongoDB网上有很多相关的资料,所以在这里不进行过多的介绍,我们在这里主要是介绍下如何将mongodb与spring boot结合使用.本节大纲: (1) 准备工作: (2) 新建一个mave ...