Fork me on GitHub

Python数据分析之pandas基本数据结构:Series、DataFrame

1引言

本文总结Pandas中两种常用的数据类型:

(1)Series是一种一维的带标签数组对象。

(2)DataFrame,二维,Series容器

2 Series数组

2.1 Series数组构成

Series数组对象由两部分构成:

  • 值(value):一维数组的各元素值,是一个ndarray类型数据。
  • 索引(index):与一维数组值一一对应的标签。利用索引,我们可非常方便得在Series数组中进行取值。

如下所示,我们通过字典创建了一个Series数组,输出结果的第一列就是索引,第二列就是数组的具体值。

>>> import pandas as pd
>>> a =pd.Series([102, 212, 332, 434])
>>> a
0 102
1 212
2 332
3 434
dtype: int64

也可以在创建时手动指定索引:

>>> a = pd.Series([102, 212, 332, 434], index=['第一列', '第二列', '第三列', '第四列'])
>>> a
第一列 102
第二列 212
第三列 332
第四列 434
dtype: int64

利用索引,我们可以更加方便得在数组中进行取值:

>>> a['第一列']
102
>>> a[['第一列', '第二列']]
第一列 102
第二列 212
dtype: int64

当然,你也可以使用以往的数字下标从数组中取值:

>>> a[0]
102
>>> a[[0,1]]
第一列 102
第二列 212
dtype: int64

2.2 创建Series数组

(1)通过list、tuple创建

>>> pd.Series([123, 321, 345,543]) # 传入一个list
0 123
1 321
2 345
3 543
dtype: int64
>>> pd.Series((123, 321, 345,543)) # 传入一个元组
0 123
1 321
2 345
3 543
dtype: int64

(2)通过传入一维numpy数组对象创建

>>> import numpy as np
>>> n = np.arange(3) # 创建一个一维的numpy数组
>>> pd.Series(n)
0 0
1 1
2 2
dtype: int32

注意:传入的numpy必须是一维的数组,否则会报错。

>>> n = np.arange(6).reshape((2,3))
>>> pd.Series(n)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
……
packages\pandas\core\internals\construction.py", line 729, in sanitize_array
raise Exception("Data must be 1-dimensional")
Exception: Data must be 1-dimensional

(3)通过传入字典创建

通过字典创建Series数组时,字典的key会自动被设置成Series数组的索引:

>>> pd.Series({'name':'张三', 'age':40, 'weight':140})
name 张三
age 40
weight 140
dtype: object

(4)通过传入一个标量值创建

当传入一个标量值时,必须传入index索引,Series会根据传入的index参数来确定数组对象的长度:

>>> a = pd.Series(10, index=['a', 'b', 'c', 'd'])
>>> a
a 10
b 10
c 10
d 10
dtype: int64

2.2 Series数组常用属性

Series数组的属性与numpy数组属性很是类似,如下表所示:

Series.index
以列表的形式返回数组的索引
Series.values
以列表的形式返回数组的所有值
Series.dtype
返回基础数据的dtype对象,数据类型
Series.shape
返回基础数据形状的元组
Series.ndim
根据定义1,数组的维数
Series.size
返回数组中的元素数
Series.base
如果与另一数组共享数据,则返回基础数组
Series.T
转置
Series.empty
判断数组是否为空
Series.name
返回系列的名称

3 DataFrame数组

3.1 DataFrame数组构成

DataFrame数组是Pandas中另一种数据结构,其数据的呈现方式类似于Excel这种二维表结构。相比于Series数组,DataFrame可以存放多维数据,所以DataFrame不仅仅有索引,还有列名,如下所示:

>>> d = {'one': [1, 2, 3, 4], 'two':['', '', '', '']}
>>> pd.DataFrame(d)
one two
0 11 22 33 4>>> df.index
RangeIndex(start=0, stop=4, step=1)
>>> df.columns
Index(['one', 'two'], dtype='object')

可以看到,DataFrame数组可以包含多维数据,类似于一张二维表。与Series类似,DataFrame数组也有一个index索引,在不指定索引时,通常会自动生成从零开始步长为1的索引。此外DataFrame数组还有一个列名,索引和列名是从数组中挑选数据的重要依据。

3.2 创建DataFrame数组

(1)通过字典创建

通过字典来创建DataFrame数组时,字典的键将会自动成DataFrame数组的列名,字典的值必须是可迭代对象,例如Series、numpy数组、list、tuple等,不同Series数组中对应的缺失值pandas将自动填充NaN:

以list列表为值的字典:

>>> d = {'one': [1, 2, 3, 4], 'two':['', '', '', '']}
>>> pd.DataFrame(d)
one two
0 11 22 33 4 四

以numpy数组为值得字典:

>>> d = {'zero': np.zeros((3,)), 'ones': np.ones((3,)), 'twos':np.full((3,),2)}
>>> pd.DataFrame(d)
zero ones twos
0 0.0 1.0 2
1 0.0 1.0 2
2 0.0 1.0 2

以Series为值的字典:

>>> 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) # 创建DataFrame数组
>>> df
one two
a 1.0 1.0
b 2.0 2.0
c 3.0 3.0
d  NaN 4.0

无论是上面那种类型对象为值的字典,都可以通过下面的方式重新指定列索引:

>>> pd.DataFrame(d, index=['d', 'b', 'a'])
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'])
two three
d 4.0 NaN
b 2.0 NaN
a 1.0 NaN

(2)通过列表创建

通过列表创建DataFrame数组时,列表的每一个元素必须是字典,这样,字典的键将作为列名。

>>> d = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}]
>>> pd.DataFrame(d)
a b c
0 1 2 NaN
1 5 10 20.0
>>> pd.DataFrame(d, index=['第一行', '第二行']) # 重新指定索引
a b c
第一行 1 2 NaN
第二行 5 10 20.0

(3)通过功能函数创建

我们还可以通过诸如from_dict()、from_records()这类的功能函数来创建DataFrame数组,以from_dict()为例:

>>> d = {'A': [1, 2, 3], 'B': [4, 5, 6]}
>>> pd.DataFrame.from_dict(d)
A B
0 1 4
1 2 5
2 3 6

如果需要让字典的键作为索引,重新指定列名,可以传入orient='index'参数,然后重新传入列名:

>>> pd.DataFrame.from_dict(d,orient='index', columns=['one', 'two', 'three'])
one two three
A 1 2 3
B 4 5 6

3.3 DataFrame数组的常用属性

DataFrame数组的属性与Series数据几乎一样,只是多了一个保存列名信息的columns属性,参看上面表格中的Series属性就行了。

4 总结

本文大致介绍了Pandas中的两种重要数据结构Series数组对象和DataFrame数组对象的特点、主要创建方法、属性。对于从数组对象中进行切片、索引数据的方法,请参考博客python数据分析之pandas数据选取:df[] df.loc[] df.iloc[] df.ix[] df.at[] df.iat[]
 
posted @ 2019-08-30 17:05  奥辰  阅读(6860)  评论(0编辑  收藏  举报