pandas入门之DataFrame
创建DataFrame
- DataFrame是一个【表格型】的数据结构。DataFrame由按一定顺序排列的多列数据组成。设计初衷是将Series的使用场景从一维拓展到多维。DataFrame既有行索引,也有列索引。
- 创建DataFrame的方式
- 列表
- 字典
- 系列
- Numpy ndarrays
- 另一个数据帧(DataFrame)
- DataFrame的参数
- data 数据采取各种形式,如:ndarray,series,map,lists,dict,constant和另一个DataFrame。
- index 对于行标签,要用于结果帧的索引是可选缺省值np.arrange(n),如果没有传递索引值。
- columns 对于列标签,可选的默认语法是 - np.arange(n)。 这只有在没有索引传递的情况下才是这样。
- dtype 每列的数据类型。
- copy 如果默认值为False,则此命令(或任何它)用于复制数据。
列表创建DataFrame
单个列表
data = [1,2,3,4,5]
df = pd.DataFrame(data)
print(df) 0
0 1
1 2
2 3
3 4
4 5
列表套列表
# 列表套列表
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=["name","age"],dtype=float) # dtype指定输出的数字类型,可加可不加
print(df) name age
0 Alex 10.0
1 Bob 12.0
2 Clarke 13.0
ndarrays/Lists[多维数组]的字典来创建DataFrame
- 所有的ndarrays必须具有相同的长度。如果传递了索引(index),则索引的长度应等于数组的长度。
- 如果没有传递索引,则默认情况下,索引将为range(n),其中n为数组长度。
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data)
print(df) # 0,1,2,3 就是range(数组)得到的值 Name Age
0 Tom 28
1 Jack 34
2 Steve 29
3 Ricky 42
指定索引
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data,index=['','','','']) # 指定索引
print(df) Name Age
1 Tom 28
2 Jack 34
3 Steve 29
4 Ricky 42
字典列表创建DataFrame 【列表中套字典】
# 字典列表可作为输入数据传递以用来创建数据帧(DataFrame),
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}] # 字典键默认为列名,没有值得为NaN
df = pd.DataFrame(data,index=["first","second"]) # 自定义行索引
print(df) a b c
first 1 2 NaN
second 5 10 20.0
使用字典,行索引和列索引列表创建DataFrame
data = [{"name":"alex","age":87,"gender":"男"},{"name":"wuchao","age":20,"gender":"男"}]
df = pd.DataFrame(data,index=[1,2],columns=["name","age","gender"]) # 自定义行索引和列索引
print(df)
name age gender
1 alex 87 男
2 wuchao 20 男
从Series的字典来创建数据帧
- 字典的系列可以传递以形成一个DataFrame。 所得到的索引是通过的所有系列索引的并集
data = {
"one":pd.Series(["","",""],index=["a","b","c"],dtype=float), # 指定数字输出类型
"tow":pd.Series(["","","",""],index=["a","b","c","d"])
}
df = pd.DataFrame(data)
print(df)
one tow
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4
numpy 创建DataFrame
pd.DataFrame(np.random.randint(60,100,size=(3,4))) # 60-100随机选择,3行4列 0 1 2 3
0 95 74 71 92
1 95 91 79 98
2 94 87 62 65
指定索引
pd.DataFrame(np.random.randint(60,100,size=(3,4)),index=["A","B","C"],columns=["a","b","c","d"]) # 60-100随机选择,3行4列 指定行索引和列索引 a b c d
A 91 70 63 98
B 98 68 88 96
C 99 77 86 66
DataFrame属性
- values 取出所有值
- columns 列索引
- index 行索引
- shape 当前表是几行几列
res = pd.DataFrame(np.random.randint(60,100,size=(3,4)),index=["A","B","C"],columns=["a","b","c","d"])
res.values # 取出所有数据
res.index # 取出行索引
res.columns # 取出列索引
res.shape # 显示当前数据是几行几列
============================================ 练习 根据以下考试成绩表,创建一个DataFrame,命名为df:
```
张三 李四
语文 150 0
数学 150 0
英语 150 0
理综 300 0
``` ============================================
dic = {
"张三":[150,150,150,300],
"李四":[0,0,0,0]
}
df = pd.DataFrame(dic,index=["语文","数学","英语","理综"])
df
张三 李四
语文 150 0
数学 150 0
英语 150 0
理综 300 0
DataFrame 索引
列索引
(1) 对列进行索引
- 通过类似字典的方式 df['q']
- 通过属性的方式 df.q
可以将DataFrame的列获取为一个Series。返回的Series拥有原DataFrame相同的索引,且name属性也已经设置好了,就是相应的列名。
res = pd.DataFrame(np.random.randint(60,100,size=(3,4)),index=["A","B","C"],columns=["a","b","c","d"])
res a b c d
A 95 83 92 89
B 70 96 92 67
C 65 69 85 78
# 属性方式
res.a
A 95
B 70
C 65
Name: a, dtype: int32
# 字典方式
res["a"]
A 95
B 70
C 65
Name: a, dtype: int32 # 修改列索引
res.columns=["aa","bb","cc","dd"]
res
aa bb cc dd
A 76 90 91 78
B 80 81 82 85
C 93 70 63 81 # 读取前两列
res[["aa","bb"]]
aa bb
A 76 90
B 80 81
C 93 70
行索引
- 使用.loc[]加index来进行行索引
- 使用.iloc[]加整数来进行行索引 同样返回一个Series,index为原来的columns。
演示
res = pd.DataFrame(np.random.randint(60,100,size=(3,4)),index=["A","B","C"],columns=["a","b","c","d"])
res
a b c d
A 91 83 96 75
B 88 92 91 60
C 73 79 72 79
查询
# loc方式
res.loc["A"] a 91
b 83
c 96
d 75
Name: A, dtype: int32 # iloc方式
res.iloc[0] a 91
b 83
c 96
d 75
Name: A, dtype: int32 res.loc[["A","B"]] a b c d
A 95 83 92 89
B 70 96 92 67
元素索引的方法
- 使用列索引
- 使用行索引(iloc[3,1] or loc['C','q']) 行索引在前,列索引在后
res = pd.DataFrame(np.random.randint(60,100,size=(3,4)),index=["A","B","C"],columns=["a","b","c","d"])
res a b c d
A 95 83 92 89
B 70 96 92 67
C 65 69 85 78
res.iloc[2,3] # 无论是行还是列 索引都是从0开始的 【78在表格中的2行3列的位置】 78 res.loc[["A","C"],"c"] # 行数据取了A/C两行得数据,列取得c列的数据 A 92
C 85
Name: c, dtype: int32
DataFrame 切片
【注意】
直接用中括号时:
- 索引表示的是列索引
- 切片表示的是行切片
res = pd.DataFrame(np.random.randint(60,100,size=(3,4)),index=["A","B","C"],columns=["a","b","c","d"])
res a b c d
A 64 60 82 97
B 64 74 63 90
C 88 68 60 71
res[1:] # 切片 表示的是行切片
a b c d
B 99 72 91 72
C 83 61 71 98
res["c"] # 索引表示的是列索引
A 82
B 63
C 60
Name: c, dtype: int32
在loc和iloc中使用切片(切列) : df.loc['B':'C','丙':'丁']
res.iloc[1,1:3] # 取第二行,b-c列的数据 顾头不顾尾
b 74
c 63
Name: B, dtype: int32 res.iloc[:,1:3] # 取所有行,b-c列数据
b c
A 60 82
B 74 63
C 68 60 res.loc["A":"C","b":"c"] # 取A-C行 b-c列数据
b c
A 60 82
B 74 63
C 68 60
DataFrame的运算
DataFrame之间的运算 同Series一样: - 在运算中自动对齐不同索引的数据
- 如果索引不对应,则补NaN
res = pd.DataFrame(np.random.randint(60,100,size=(3,4)),index=["A","B","C"],columns=["a","b","c","d"])
ret = pd.DataFrame(np.random.randint(60,100,size=(3,4)),index=["A","B","C"],columns=["a","b","c","f"])
res + ret a b c d f
A 138 174 173 NaN NaN
B 142 168 180 NaN NaN
C 160 156 187 NaN NaN
pandas入门之DataFrame的更多相关文章
- 利用Python进行数据分析——pandas入门
利用Python进行数据分析--pandas入门 基于NumPy建立的 from pandas importSeries,DataFrame,import pandas as pd 一.两种数据结构 ...
- Python 数据处理库 pandas 入门教程
Python 数据处理库 pandas 入门教程2018/04/17 · 工具与框架 · Pandas, Python 原文出处: 强波的技术博客 pandas是一个Python语言的软件包,在我们使 ...
- 利用python进行数据分析之pandas入门
转自https://zhuanlan.zhihu.com/p/26100976 目录: 5.1 pandas 的数据结构介绍5.1.1 Series5.1.2 DataFrame5.1.3索引对象5. ...
- 利用python进行数据分析--pandas入门2
随书练习,第五章 pandas入门2 # coding: utf-8 # In[1]: from pandas import Series,DataFrame import pandas as pd ...
- 利用python进行数据分析--pandas入门1
随书练习,第五章 pandas入门1 # coding: utf-8 # In[1]: from pandas import Series, DataFrame # In[2]: import pa ...
- pandas 入门(3)
from pandas import Series, DataFrame, Index import numpy as np # 层次化索引 对数据重塑和分组操作很有用 data = Series(n ...
- < 利用Python进行数据分析 - 第2版 > 第五章 pandas入门 读书笔记
<利用Python进行数据分析·第2版>第五章 pandas入门--基础对象.操作.规则 python引用.浅拷贝.深拷贝 / 视图.副本 视图=引用 副本=浅拷贝/深拷贝 浅拷贝/深拷贝 ...
- pandas 学习(2): pandas 数据结构之DataFrame
DataFrame 类型类似于数据库表结构的数据结构,其含有行索引和列索引,可以将DataFrame 想成是由相同索引的Series组成的Dict类型.在其底层是通过二维以及一维的数据块实现. 1. ...
- 《利用python进行数据分析》读书笔记--第五章 pandas入门
http://www.cnblogs.com/batteryhp/p/5006274.html pandas是本书后续内容的首选库.pandas可以满足以下需求: 具备按轴自动或显式数据对齐功能的数据 ...
随机推荐
- (九)springmvc之json的数据请求(客户端发送json数据到服务端)
index.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pag ...
- AngularJS视图 ng-view
AngularJS支持通过在单个页面上的多个视图的单页应用.要做到这一点AngularJS提供ng-view 和 ng-template指令,以及 $routeProvider 服务. ng-view ...
- Linux装好系统之后配置环境
1.配置IP地址vi /etc/sysconfig/network-scripts/ifcfg-eth0 ONBOOT=yes NM_CONTROLLED=yes BOOTPROTO=static D ...
- [JZOJ5897]密匙--哈希骚操作
[JZOJ5897]密匙--哈希骚操作 题目链接 太懒了自行Google 前置技能 二分/倍增求LCP e.g TJOI2017DNA 分析 这题看了样例解释才知道什么意思 本以为自己身为mo法师蛤希 ...
- 使用Java Executor框架实现多线程
本文将涵盖两个主题: 通过实现Callable接口创建线程 在Java中使用Executor框架 实现Callable接口 为了创建一段可以在线程中运行的代码,我们创建了一个类,然后实现了Callab ...
- 如何判断 Session是否存在
相信很多人都跟我一样,在写网页中有些位置通过其他网页设置了 Session然后跳转到目标页面就需要要用 Session,但是那个位置如果是直接打开的就用不到 Session,那么问题就来了,例如:系统 ...
- springboot启动流程(十二)springboot事务自动配置
所有文章 https://www.cnblogs.com/lay2017/p/11478237.html 正文 在上一篇文章中,我们简单了解了aop的处理过程.代理增强之前,先生成Advisor,然后 ...
- 基于【 centos7】四 || FastDFS集群+Nginx负载均衡
1. 架构设计 1.1 架构图 FastDFS是用c语言编写的一款开源的分布式文件系统.FastDFS为互联网量身定制,充分考虑了冗余备份.负载均衡.线性扩容等机制,并注重高可用.高性能等指标,使用F ...
- 【转】DELPHI开始支持LINUX DOCKER
这是咏南翻译Marco Cantu的文章. 在过去的几年中,将服务器端解决方案(实际上是任何类型的应用程序)部署到轻量级DOCKER而不是物理机器或虚拟机已经变得越来越普遍,因为这允许更大的灵活性(在 ...
- 用Python来使用科大讯飞语音识别,so easy
在人工智能高速发展的今天,语音识别技术被带入到人们的工作和生活中,开始被越来越多的人关注和使用,今天,当各种在线客服被机器人客服代替,当速记翻译馆被语音识别代替,甚至当收银员.驾驶员.工厂工人.普通文 ...