简介

本文将会讲解Pandas中基本的数据类型Series和DataFrame,并详细讲解这两种类型的创建,索引等基本行为。

使用Pandas需要引用下面的lib:

In [1]: import numpy as np

In [2]: import pandas as pd

Series

Series是一维带label和index的数组。我们使用下面的方法来创建一个Series:

>>> s = pd.Series(data, index=index)

这里的data可以是Python的字典,np的ndarray,或者一个标量。

index是一个横轴label的list。接下来我们分别来看下怎么创建Series。

ndarray创建

s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])

s
Out[67]:
a -1.300797
b -2.044172
c -1.170739
d -0.445290
e 1.208784
dtype: float64

使用index获取index:

s.index
Out[68]: Index(['a', 'b', 'c', 'd', 'e'], dtype='object')

从dict创建

d = {'b': 1, 'a': 0, 'c': 2}

pd.Series(d)
Out[70]:
a 0
b 1
c 2
dtype: int64

从标量创建

pd.Series(5., index=['a', 'b', 'c', 'd', 'e'])
Out[71]:
a 5.0
b 5.0
c 5.0
d 5.0
e 5.0
dtype: float64

Series 和 ndarray

Series和ndarray是很类似的,在Series中使用index数值表现的就像ndarray:

s[0]
Out[72]: -1.3007972194268396 s[:3]
Out[73]:
a -1.300797
b -2.044172
c -1.170739
dtype: float64 s[s > s.median()]
Out[74]:
d -0.445290
e 1.208784
dtype: float64 s[[4, 3, 1]]
Out[75]:
e 1.208784
d -0.445290
b -2.044172
dtype: float64

Series和dict

如果使用label来访问Series,那么它的表现就和dict很像:

s['a']
Out[80]: -1.3007972194268396 s['e'] = 12. s
Out[82]:
a -1.300797
b -2.044172
c -1.170739
d -0.445290
e 12.000000
dtype: float64

矢量化操作和标签对齐

Series可以使用更加简单的矢量化操作:

s + s
Out[83]:
a -2.601594
b -4.088344
c -2.341477
d -0.890581
e 24.000000
dtype: float64 s * 2
Out[84]:
a -2.601594
b -4.088344
c -2.341477
d -0.890581
e 24.000000
dtype: float64 np.exp(s)
Out[85]:
a 0.272315
b 0.129487
c 0.310138
d 0.640638
e 162754.791419
dtype: float64

Name属性

Series还有一个name属性,我们可以在创建的时候进行设置:

s = pd.Series(np.random.randn(5), name='something')

s
Out[88]:
0 0.192272
1 0.110410
2 1.442358
3 -0.375792
4 1.228111
Name: something, dtype: float64

s还有一个rename方法,可以重命名s:

s2 = s.rename("different")

DataFrame

DataFrame是一个二维的带label的数据结构,它是由Series组成的,你可以把DataFrame看成是一个excel表格。DataFrame可以由下面几种数据来创建:

  • 一维的ndarrays, lists, dicts, 或者 Series
  • 结构化数组创建
  • 2维的numpy.ndarray
  • 其他的DataFrame

从Series创建

可以从Series构成的字典中来创建DataFrame:

d = {'one': pd.Series([1., 2., 3.], index=['a', 'b', 'c']),'two': pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)

df
Out[92]:
one two
a 1.0 1.0
b 2.0 2.0
c 3.0 3.0
d NaN 4.0

进行index重排:

pd.DataFrame(d, index=['d', 'b', 'a'])
Out[93]:
one two
d NaN 4.0
b 2.0 2.0
a 1.0 1.0

进行列重排:

pd.DataFrame(d, index=['d', 'b', 'a'], columns=['two', 'three'])
Out[94]:
two three
d 4.0 NaN
b 2.0 NaN
a 1.0 NaN

从ndarrays 和 lists创建

d = {'one': [1., 2., 3., 4.],'two': [4., 3., 2., 1.]}

pd.DataFrame(d)
Out[96]:
one two
0 1.0 4.0
1 2.0 3.0
2 3.0 2.0
3 4.0 1.0 pd.DataFrame(d, index=['a', 'b', 'c', 'd'])
Out[97]:
one two
a 1.0 4.0
b 2.0 3.0
c 3.0 2.0
d 4.0 1.0

从结构化数组创建

可以从结构化数组中创建DF:

In [47]: data = np.zeros((2, ), dtype=[('A', 'i4'), ('B', 'f4'), ('C', 'a10')])

In [48]: data[:] = [(1, 2., 'Hello'), (2, 3., "World")]

In [49]: pd.DataFrame(data)
Out[49]:
A B C
0 1 2.0 b'Hello'
1 2 3.0 b'World' In [50]: pd.DataFrame(data, index=['first', 'second'])
Out[50]:
A B C
first 1 2.0 b'Hello'
second 2 3.0 b'World' In [51]: pd.DataFrame(data, columns=['C', 'A', 'B'])
Out[51]:
C A B
0 b'Hello' 1 2.0
1 b'World' 2 3.0

从字典list创建

In [52]: data2 = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}]

In [53]: pd.DataFrame(data2)
Out[53]:
a b c
0 1 2 NaN
1 5 10 20.0 In [54]: pd.DataFrame(data2, index=['first', 'second'])
Out[54]:
a b c
first 1 2 NaN
second 5 10 20.0 In [55]: pd.DataFrame(data2, columns=['a', 'b'])
Out[55]:
a b
0 1 2
1 5 10

从元组中创建

可以从元组中创建更加复杂的DF:

In [56]: pd.DataFrame({('a', 'b'): {('A', 'B'): 1, ('A', 'C'): 2},
....: ('a', 'a'): {('A', 'C'): 3, ('A', 'B'): 4},
....: ('a', 'c'): {('A', 'B'): 5, ('A', 'C'): 6},
....: ('b', 'a'): {('A', 'C'): 7, ('A', 'B'): 8},
....: ('b', 'b'): {('A', 'D'): 9, ('A', 'B'): 10}})
....:
Out[56]:
a b
b a c a b
A B 1.0 4.0 5.0 8.0 10.0
C 2.0 3.0 6.0 7.0 NaN
D NaN NaN NaN NaN 9.0

列选择,添加和删除

可以像操作Series一样操作DF:

In [64]: df['one']
Out[64]:
a 1.0
b 2.0
c 3.0
d NaN
Name: one, dtype: float64 In [65]: df['three'] = df['one'] * df['two'] In [66]: df['flag'] = df['one'] > 2 In [67]: df
Out[67]:
one two three flag
a 1.0 1.0 1.0 False
b 2.0 2.0 4.0 False
c 3.0 3.0 9.0 True
d NaN 4.0 NaN False

可以删除特定的列,或者pop操作:

In [68]: del df['two']

In [69]: three = df.pop('three')

In [70]: df
Out[70]:
one flag
a 1.0 False
b 2.0 False
c 3.0 True
d NaN False

如果插入常量,那么会填满整个列:

In [71]: df['foo'] = 'bar'

In [72]: df
Out[72]:
one flag foo
a 1.0 False bar
b 2.0 False bar
c 3.0 True bar
d NaN False bar

默认会插入到DF中最后一列,可以使用insert来指定插入到特定的列:

In [75]: df.insert(1, 'bar', df['one'])

In [76]: df
Out[76]:
one bar flag foo one_trunc
a 1.0 1.0 False bar 1.0
b 2.0 2.0 False bar 2.0
c 3.0 3.0 True bar NaN
d NaN NaN False bar NaN

使用assign 可以从现有的列中衍生出新的列:

In [77]: iris = pd.read_csv('data/iris.data')

In [78]: iris.head()
Out[78]:
SepalLength SepalWidth PetalLength PetalWidth Name
0 5.1 3.5 1.4 0.2 Iris-setosa
1 4.9 3.0 1.4 0.2 Iris-setosa
2 4.7 3.2 1.3 0.2 Iris-setosa
3 4.6 3.1 1.5 0.2 Iris-setosa
4 5.0 3.6 1.4 0.2 Iris-setosa In [79]: (iris.assign(sepal_ratio=iris['SepalWidth'] / iris['SepalLength'])
....: .head())
....:
Out[79]:
SepalLength SepalWidth PetalLength PetalWidth Name sepal_ratio
0 5.1 3.5 1.4 0.2 Iris-setosa 0.686275
1 4.9 3.0 1.4 0.2 Iris-setosa 0.612245
2 4.7 3.2 1.3 0.2 Iris-setosa 0.680851
3 4.6 3.1 1.5 0.2 Iris-setosa 0.673913
4 5.0 3.6 1.4 0.2 Iris-setosa 0.720000

注意, assign 会创建一个新的DF,原DF保持不变。

下面用一张表来表示DF中的index和选择:

操作 语法 返回结果
选择列 df[col] Series
通过label选择行 df.loc[label] Series
通过数组选择行 df.iloc[loc] Series
行的切片 df[5:10] DataFrame
使用boolean向量选择行 df[bool_vec] DataFrame

本文已收录于 http://www.flydean.com/03-python-pandas-data-structures/

最通俗的解读,最深刻的干货,最简洁的教程,众多你不知道的小技巧等你来发现!

欢迎关注我的公众号:「程序那些事」,懂技术,更懂你!

Pandas之:深入理解Pandas的数据结构的更多相关文章

  1. pandas教程1:pandas数据结构入门

    pandas是一个用于进行python科学计算的常用库,包含高级的数据结构和精巧的工具,使得在Python中处理数据非常快速和简单.pandas建造在NumPy之上,它使得以NumPy为中心的应用很容 ...

  2. 数据分析 Pandas 简介和它的的数据结构

    本文主要讲Pandas 的Series和DataFrame 的相关属性和操作 1.Series的相关属性和操作# --Series是一种类似于一维数组的对象,只能存放一维数组!由以下两部分组成:# v ...

  3. 【跟着stackoverflow学Pandas】 -Get list from pandas DataFrame column headers - Pandas 获取列名

    最近做一个系列博客,跟着stackoverflow学Pandas. 以 pandas作为关键词,在stackoverflow中进行搜索,随后安照 votes 数目进行排序: https://stack ...

  4. Python:pandas(二)——pandas函数

    Python:pandas(一) 这一章翻译总结自:pandas官方文档--General functions 空值:pd.NaT.np.nan //判断是否为空 if a is np.nan: .. ...

  5. 深入理解pandas读取excel,txt,csv文件等命令

    pandas读取文件官方提供的文档 在使用pandas读取文件之前,必备的内容,必然属于官方文档,官方文档查阅地址 http://pandas.pydata.org/pandas-docs/versi ...

  6. 初探pandas——安装和了解pandas数据结构

    安装pandas 通过python pip安装pandas pip install pandas pandas数据结构 pandas常用数据结构包括:Series和DataFrame Series S ...

  7. Python之Pandas的一些理解

    Pandas的功能: 1.  结构化的数据分析; 相比excel,可以处理更大量的数据和更好的性能 2.  对数据的清洗

  8. 基于 Python 和 Pandas 的数据分析(2) --- Pandas 基础

    在这个用 Python 和 Pandas 实现数据分析的教程中, 我们将明确一些 Pandas 基础知识. 加载到 Pandas Dataframe 的数据形式可以很多, 但是通常需要能形成行和列的数 ...

  9. python之pandas学习笔记-初识pandas

    初识pandas python最擅长的就是数据处理,而pandas则是python用于数据分析的最常用工具之一,所以学python一定要学pandas库的使用. pandas为python提供了高性能 ...

随机推荐

  1. Python练习1-文档格式化成html

    文档格式化成HTML 把文档格式化成了THML,并没有处理所有thml规则,只是处理了一部分,功能不重要,重要的是复习熟悉下Python对文档的处理细节.毕竟Python大多数给我的印象都是处理文档. ...

  2. 源码分析SpringCloud Gateway如何加载断言(predicates)与过滤器(filters)

    我们今天的主角是Gateway网关,一听名字就知道它基本的任务就是去分发路由.根据不同的指定名称去请求各个服务,下面是Gateway官方的解释: https://spring.io/projects/ ...

  3. ppt技巧--字体变化

    常见字体搭配 Nordri Tools

  4. 简单说几个MySQL高频面试题

    前言: 在各类技术岗位面试中,似乎 MySQL 相关问题经常被问到.无论你面试开发岗位或运维岗位,总会问几道数据库问题.经常有小伙伴私信我,询问如何应对 MySQL 面试题.其实很多面试题都是大同小异 ...

  5. Rabbit MQ一些参数解释

    //ConnectionFactory(连接工厂): 生产Connection的的工厂 //Connection(连接):是RabbitMQ的socket的长链接,它封装了socket协议相关部分逻辑 ...

  6. 折腾Linux内核编译

    计网提高实验.指导书给的是远古版本2.6.39.2,轻易在某hub上找到下载地址 查表 看起来Ubuntu 11.04离得最近,遂下一个镜像 懒得上google检索了,编译准备先follow这篇博客试 ...

  7. 不融资、不上市、不快马圈地…“佛系”ZOHO的中国生意经

    来源:钛媒体 作者:秦聪慧 "技术比肩SAP.直追微软的这家25岁"非典型"国际大厂会继续佛系下去吗? ZOHO研发中心大楼 在中国,有家相对低调的"舶来&qu ...

  8. ==与equals比较

    提到==与equals的区别,这就必须先回顾一下jvm内存的分配机制 ==和equals无非比较两个基本数据类型或者对象类型 八种基本类型: 基本类型 大小 默认值 封装类 byte 1 0 Byte ...

  9. linux自动化交互脚本expect详解set timeout 5是 意思是在expect语句中,5s后超时,不再作出选择。

    linux自动化交互脚本expect详解  更新时间:2020年10月21日 10:13:20   作者:lendsomething     这篇文章主要介绍了linux自动化交互脚本expect的相 ...

  10. 使用 IPMI 远程为服务器安装操作系统教程

    使用 IPMI 远程为服务器安装操作系统教程 shida_csdn 2019-01-09 11:30:10 9588 收藏 16展开一.什么是 IPMI? IPMI 是智能平台管理接口(Intelli ...