pandas中数据结构-Series

pandas中数据结构-Series

pandas简介

Pandas是一个开源的,BSD许可的Python库,为Python编程语言提供了高性能,易于使用的数据结构和数据分析工具。Python与Pandas一起使用的领域广泛,包括学术和商业领域,包括金融,经济学,统计学,分析等。在本教程中,我们将学习PythonPandas的各种功能以及如何在实践中使用它们。

pandas安装

安装

pip install pandas

导入

import pandas as pd
from pandas import Series, DataFrame

Series介绍

Series是一种类似于一维数组的对象,它由一组数据(各种NumPy数据类型)以及一组与之相关的数据标签(即索引)组成。仅由一组数据即可产生最简单的Series:

>>> import pandas as pd
>>> obj=pd.Series([4,7,-5,3])
>>> obj
0    4
1    7
2   -5
3    3
dtype: int64

Series的组成

Series的字符串表现形式为:索引在左边,值在右边。由于我们没有为数据指定索引,于是会自动创建一个0到N-1(N为数据的长度)的整数型索引。你可以通过Series 的values和index属性获取其数组表示形式和索引对象:

  • 索引
>>> import pandas as pd
>>> obj.values
array([ 4,  7, -5,  3], dtype=int64)
>>> obj.index
RangeIndex(start=0, stop=4, step=1)

Series自定义索引

通常,我们希望所创建的Series带有一个可以对各个数据点进行标记的索引:索引和值是一一对应的关系

>>> obj2=pd.Series([4,7,-5,3],index=['d','b','a','c'])
>>> obj2
d    4
b    7
a   -5
c    3
dtype: int64

Series通过索引来获取值

>>> obj2['a']
-5
>>> obj2['d']
4
>>> obj2['c','a','d']
>>> obj2[['c','a','d']]
c    3
a   -5
d    4
dtype: int64

Series运算

>>> obj2[obj2>0]
d    4
b    7
c    3
dtype: int64
>>> obj2*2
d     8
b    14
a   -10
c     6
dtype: int64
>>> import numpy as np
>>> np.exp(obj2)
d      54.598150
b    1096.633158
a       0.006738
c      20.085537
dtype: float64

Series和字典的关系

还可以将Series看成是一个定长的有序字典,因为它是索引值到数据值的一个映射。它可以用在许多原本需要字典参数的函数中:

判断索引是否存在

>>> 'b' in obj2
True
>>> 'e' in obj2
False

根据字典来创建

1.传入一个字典来创建一个Series

>>> sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000}
>>> obj3=pd.Series(sdata)
>>> obj3
Ohio      35000
Texas     71000
Oregon    16000
Utah       5000
dtype: int64

2.传入新的索引来改变字典的顺序

由于新增的California没有值与它对应,所以表示数据缺失

>>> states = ['California', 'Ohio', 'Oregon', 'Texas']
>>> obj4 = pd.Series(sdata, index=states)
>>> obj4
California        NaN
Ohio          35000.0
Oregon        16000.0
Texas         71000.0
dtype: float64

3.检测数据的缺失

>>> pd.isnull(obj4)
California     True
Ohio          False
Oregon        False
Texas         False
dtype: bool
>>> pd.notnull(obj4)
California    False
Ohio           True
Oregon         True
Texas          True
dtype: bool

Series利用索引标签对齐数据

简单的说就是对应索引的值相加

>>> obj3
Ohio      35000
Texas     71000
Oregon    16000
Utah       5000
dtype: int64
>>> obj4
California        NaN
Ohio          35000.0
Oregon        16000.0
Texas         71000.0
dtype: float64
>>> obj3+obj4
California         NaN
Ohio           70000.0
Oregon         32000.0
Texas         142000.0
Utah               NaN
dtype: float64

Series修改name值

>>> obj4.name='population'
>>> obj4.index.name='state'
>>> obj4
state
California        NaN
Ohio          35000.0
Oregon        16000.0
Texas         71000.0
Name: population, dtype: float64

Series通过赋值修改索引

>>> obj
0    4
1    7
2   -5
3    3
dtype: int64
>>> obj.index=['Bob','Steve','Jeff','Ryan']
>>> obj
Bob      4
Steve    7
Jeff    -5
Ryan     3
dtype: int64
posted @ 2019-10-10 10:40  梦小冷  阅读(279)  评论(0编辑  收藏  举报