Pandas的数据结构

本文详细介绍了Pandas中的两种核心数据结构——Series和DataFrame。Series是一维数据结构,类似于一维数组,可从数组、字典等创建,并具有自动对齐和dict-like属性。DataFrame是二维数据结构,类似于表格,支持多种数据类型,可以从字典、数组等创建,具有列标签选取、增加、删除等操作。文章强调了数据对齐和不可变性的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

 

概述

Series

Series的创建

like-array类型数据创建Series

Dict创建Series

标量创建Series

Series的特点

Series is ndarray-like

Series is dict-like

矢量化操作和标签自动对齐

Name属性 

DataFrame

DataFrame的创建

From dict of Series or dicts

From dict of ndarrays / lists

From structured or record array

From a list of dicts

From a dict of tuples

From a Series

DataFrame.from_dict构造函数

DataFrame.from_records构造函数 

列标签的选取、增加、删除

方法链中分配新列(Assigning New Columns in Method Chains)

索引/选择(Indexing / Selection)

数据的对齐和算法(Data alignment and arithmetic)

转置(Transposing) 

与Numpy函数的互操作性(DataFrame interoperability with NumPy functions)

显示控制(Console display)

IPython在DataFrame列属性访问时的自动补全

(DataFrame column attribute access and IPython completion)

小结


概述

Pandas库的数据结构是依赖于Numpy库的ndarray发展而来的.

Pandas中只有三种类型的数据结构,对比如下:

类型 维度(dim) 形状(shape) 元素类型 说明
ndarray(Numpy) 1或2 1×0或者n×m 同构 一维的数组或者多维的矩阵,无索引
Series 1 m×1 非同构 带索引的一维数组
DataFrame 2 m×n 非同构 由多个Series组成的二维表,可以理解为Series容器
Panel 3 m×n×h 非同构 三维,可以理解为DataFrame容器(将被更高版本的Pandas遗弃

鉴于Pandas官方已经声明在以后更高版本的Pandas中,因为使用率低的问题,将抛弃对Pannel的支持,所以本文将不在对Pannel结构进行介绍,仅仅介绍常用的Series和DataFrame. Series和DataFrame数据结构的主要属性:

属性 说明
index 返回索引
columns 返回字段名(列名),Series无该属性,但有name属性
values 返回索引元素组成的array
dtypes 返回元素类型
ndim 返回维度
shape 返回形状
size 返回所有元素个数
itemsize 返回每个元素所占大小(字节为单位),DataFrame无该属性

构造一个用于演示的DataFrame来看看主要的属性:

import pandas as pd
import numpy as np

#制造数据:
np.random.seed(100)
data=np.random.randint(1,10,40).reshape(8,-1)
index=pd.date_range('20180901',periods=8)
col=list('ABCDE')
df=pd.DataFrame(data,index=index,columns=col)
print(df)
#输出:
            A  B  C  D  E
2018-09-01  7  8  1  1  8
2018-09-02  1  5  6  3  2
2018-09-03  3  6  6  1  5
2018-09-04  5  8  6  3  3
2018-09-05  9  9  7  1  1
2018-09-06  8  1  4  5  8
2018-09-07  8  1  2  1  9
2018-09-08  7  8  4  1  6

 查看该对象的属性:

print('index属性: ',df.index)
print('我是分割线'.center(80,'='))
print('columns属性:',df.columns)
print('我是分割线'.center(80,'='))
print('values属性:',df.values)
print('我是分割线'.center(80,'='))
print('dtypes属性:',df.dtypes)
print('我是分割线'.center(80,'='))
print('ndim属性:',df.ndim)
print('我是分割线'.center(80,'='))
print('shape属性:',df.shape)
print('我是分割线'.center(80,'='))
print('size属性:',df.size)
-------------------------------------------------------------------------------------
index属性:  DatetimeIndex(['2018-09-01', '2018-09-02', '2018-09-03', '2018-09-04',
               '2018-09-05', '2018-09-06', '2018-09-07', '2018-09-08'],
              dtype='datetime64[ns]', freq='D')
=====================================我是分割线======================================
columns属性: Index(['A', 'B', 'C', 'D', 'E'], dtype='object')
=====================================我是分割线======================================
values属性: [[9 9 4 8 8]
 [1 5 3 6 3]
 [3 3 2 1 9]
 [5 1 7 3 5]
 [2 6 4 5 5]
 [4 8 2 2 8]
 [8 1 3 4 3]
 [6 9 2 1 8]]
=====================================我是分割线======================================
dtypes属性: A    int32
B    int32
C    int32
D    int32
E    int32
dtype: object
=====================================我是分割线======================================
ndim属性: 2
=====================================我是分割线======================================
shape属性: (8, 5)
=====================================我是分割线======================================
size属性: 40

Series

Series是一维的数据结构,可以理解为继承于的一维的ndarray.

Series同时也是Pandas中的基础性的数据结构,DataFrame的每一列数据都是Series,也就是说Series构成了DataFrame.

Series的创建

Series的创建主要使用pd.Series(data, index)方法

其中data参数可以是数组,字典,列表等等类序列数据,甚至也可以是标量值(比如数字5,字母A)

index参数表示的是Series的索引列表,根据data参数的不同设定不同的index参数.

下面介绍几种主要的Series的创建方式.

like-array类型数据创建Series

如果data参数是like-array(类数组)类型,那么index参数的长度必须与data参数的数组长度一致.

如果不指定index参数的话,那么Pandas将按照[0, ..., len(data) - 1]的原则自动创建index索引

pd.Series(np.random.randint(1,10,4),index=list('abcd'))
Out[4]: 
a    7
b    1
c    4
d    4
dtype: int32

pd.Series([1,2,3],index=['A','B','C'])
Out[5]: 
A    1
B    2
C    3
dtype: int64

Dict创建Series

从dict创建Series若不指定index参数则默认为dict的key

若指定index参数,则指定的index序列与dict.keys序列的交集作有value的索引

而在dict.keys需要中匹配不到的index元素的value值为NaN

NaN是Pandas中的一个标准的缺失值代表,表示not a number的意思

#高版本:
pd.Series({'b' : 1, 'a' : 0, 'c' : 2})
Out[7]: 
b    1
a    0
c    2
dtype: int64

#低版本:
pd.Series({'b' : 1, 'a' : 0, 'c' : 2})
Out[7]: 
a    0
b    1
c    2
dtype: int64

pd.Series({'b' : 1, 'a' : 0, 'c' : 2},index=list('abK'))
Out[8]: 
a    0.0
b    1.0
K    NaN
dtype: float64

从Dcit数据创建的Series对象的数据排列顺序与使用的Python和Pandas版本相关.

Python版本高于3.6,Pandas版本高于0.23,那么数据排列顺序与dict数据插入的顺序一致

若 Python版本低于3.6,Pandas版本低于0.23,那么数据排列顺序以dict中键值的字符顺序为标准.

标量创建Series

如果以标量来创建Series,则必须指定index参数,且Series的value值会自动重复到index参数的长度.

pd.Series(5,index=list('abc'))
Out[9]: 
a    5
b    5
c    5
dtype: int64
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值