pandas入门指南
上一篇讲了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入门指南的更多相关文章
- Web API 入门指南 - 闲话安全
Web API入门指南有些朋友回复问了些安全方面的问题,安全方面可以写的东西实在太多了,这里尽量围绕着Web API的安全性来展开,介绍一些安全的基本概念,常见安全隐患.相关的防御技巧以及Web AP ...
- Vue.js 入门指南之“前传”(含sublime text 3 配置)
题记:关注Vue.js 很久了,但就是没有动手写过一行代码,今天准备入手,却发现自己比菜鸟还菜,于是四方寻找大牛指点,才终于找到了入门的“入门”,就算是“入门指南”的“前传”吧.此文献给跟我一样“白痴 ...
- yii2实战教程之新手入门指南-简单博客管理系统
作者:白狼 出处:http://www.manks.top/document/easy_blog_manage_system.html 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文 ...
- 【翻译】Fluent NHibernate介绍和入门指南
英文原文地址:https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started 翻译原文地址:http://www.cnblogs ...
- ASP.NET MVC 5 入门指南汇总
经过前一段时间的翻译和编辑,我们陆续发出12篇ASP.NET MVC 5的入门文章.其中大部分翻译自ASP.NET MVC 5 官方教程,由于本系列文章言简意赅,篇幅适中,从一个web网站示例开始讲解 ...
- 一起学微软Power BI系列-官方文档-入门指南(1)Power BI初步介绍
我们在前一篇文章微软新神器-Power BI,一个简单易用,还用得起的BI产品中,我们初步介绍了Power BI的基本知识.由于Power BI是去年开始微软新发布的一个产品,虽然已经可以企业级应用, ...
- 一起学微软Power BI系列-官方文档-入门指南(2)获取源数据
我们在文章: 一起学微软Power BI系列-官方文档-入门指南(1)Power BI初步介绍中,我们介绍了官方入门文档的第一章.今天继续给大家介绍官方文档中,如何获取数据源的相关内容.虽然是英文,但 ...
- 一起学微软Power BI系列-官方文档-入门指南(3)Power BI建模
我们前2篇文章:一起学微软Power BI系列-官方文档-入门指南(1)Power BI初步介绍 和一起学微软Power BI系列-官方文档-入门指南(2)获取源数据 中,我们介绍了官方入门文档与获取 ...
- 一起学微软Power BI系列-官方文档-入门指南(4)Power BI的可视化
在前面的系列文章中,我们介绍了官方有关获取数据,以及建模的原始文档和基本介绍.今天继续给大家介绍官方文档中,有关可视化的内容.实际上获获取数据和建模更注重业务关系的处理,而可视化则关注对数据的解读.这 ...
随机推荐
- Python操作12306抢票脚本
有一段时间没有使用Python了,前几天经朋友提起一篇关于用Python实现抢火车票的文章,百度了实现抢火车票的技术细节,网上却有不少资料,也不是新鲜的东西.在了解了一些技术手段,阅读了一些大神的博文 ...
- perl学习之:正则表达式
- Web框架之Django_03 路由层了解(路有层 无名分组、有名分组、反向解析、路由分发 视图层 JsonResponse,FBV、CBV、文件上传)
摘要: 路由层 无名分组 有名分组 反向解析 路由分发 名称空间 伪静态网页.虚拟环境 视图层 JsonResponse FBV 与 CBV(function base views与class bas ...
- Python9-day3-作业
ascli 字母,数字.特殊字符,1个字节.8位 unicode:16位 两个字节,升级32位,四个字节 utf-8:最少一个字节 8位,英文字母, 1,有变量name = "aleX l ...
- raywenderlich.com Objective-C编码规范
原文链接 : The official raywenderlich.com Objective-C style guide 原文作者 : raywenderlich.com Team 译文出自 : r ...
- 关于get_magic_quotes_gpc()函数
function sqlReplace($str) { $strResult = $str; if(!get_magic_quotes_gpc()) //如果 gpc 没有开的话 { $strResu ...
- 16,re模块的常用方法
ret =re.findall('\d+', 'eva123egon4yuan567') print(ret)#返回满足条件的结果 ,放在一个列表里. ret2 = re.search('\d+',' ...
- 大数据学习——Storm学习单词计数案例
需求:计算单词在文档中出现的次数,每出现一次就累加一次 遇到的问题 这个问题是<scope>provided</scope>作用域问题 https://www.cnblogs. ...
- TOJ 4804: 树网的核
这个是NOIP的提高组的题 4804: 树网的核 Time Limit(Common/Java):1000MS/3000MS Memory Limit:65536KByteTotal Sub ...
- Educational Codeforces Round 24
A. Diplomas and Certificates time limit per test 1 second memory limit per test 256 megabytes input ...