pandas 学习一: pandas 数据结构之Series

1. Series

  Series 是一个类数组的数据结构,同时带有标签(lable)或者说索引(index)。

  1.1 下边生成一个最简单的Series对象,因为没有给Series指定索引,所以此时会使用默认索引(从0到N-1)。

from pandas import Series,DataFrame
import pandas as pd
ser1 = pd.Series([11,22,33,44])
print ser1
0    11
1    22
2    33
3    44
dtype: int64

取索引3对应的数据:

ser1[3]
Out[44]: 44

1.2 当要生成一个指定索引的Series 时候,写法如下:

ser2 = pd.Series(range(4),index = ["a","b","c","d"])
print ser2
a    0
b    1
c    2
d    3
dtype: int64

1.3 也可以通过字典来创建Series对象

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

在用字典生成Series的时候,也可以指定索引,当索引中值对应的字典中的值不存在的时候,则此索引的值标记为Missing,NA,并且可以通过函数(pandas.isnull,pandas.notnull)来确定哪些索引对应的值是没有的。

states = ['California', 'Ohio', 'Oregon', 'Texas']
ser4=pd.Series(sdata,index=states)
print ser4
California        NaN
Ohio          35000.0
Oregon        16000.0

# 判断哪些值为空
pd.isnull(ser4)
Out[54]: 
California     True
Ohio          False
Oregon        False
Texas         False
dtype: bool
pd.notnull(ser4)
Out[55]: 
California    False
Ohio           True
Oregon         True
Texas          True
dtype: bool

1.4 访问Series中的元素和索引:

ser2['a']
Out[56]: 0
ser2[['a','c']]
Out[57]: 
a    0
c    2
dtype: int64
ser2.values
Out[58]: array([0, 1, 2, 3], dtype=int64)
ser2.index
Out[59]: Index([u'a', u'b', u'c', u'd'], dtype='object')

1.5 简单运算

  在pandas的Series中,会保留NumPy的数组操作(用布尔数组过滤数据,标量乘法,以及使用数学函数),并同时保持引用的使用

dtype: int64
ser2[ser2>2]
Out[61]: 
d    3
dtype: int64
ser2[ser2>=2]
Out[62]: 
c    2
d    3
dtype: int64
ser2*3
Out[63]: 
a    0
b    3
c    6
d    9
dtype: int64
np.exp(ser2)
Out[64]: 
a     1.000000
b     2.718282
c     7.389056
d    20.085537
dtype: float64

1.6 Series的自动对齐

    Series的一个重要功能就是自动对齐(不明觉厉),看看例子就明白了。 差不多就是不同Series对象运算的时候根据其索引进行匹配计算。


ser3
Out[67]: 
Ohio      35000
Oregon    16000
Texas     71000
Utah       5000
dtype: int64
ser4
Out[68]: 
California        NaN
Ohio          35000.0
Oregon        16000.0
Texas         71000.0
dtype: float64
ser3+ser4
Out[69]: 
California         NaN
Ohio           70000.0
Oregon         32000.0
Texas         142000.0
Utah               NaN
dtype: float64

1.7 命名

  Series对象本身,以及索引都有一个 name 属性


ser4.index.name='state'
ser4.name='population'
ser4
Out[73]: 
state
California        NaN
Ohio          35000.0
Oregon        16000.0
Texas         71000.0
Name: population, dtype: float64
ser4.abs()
Out[74]: 
state
California        NaN
Ohio          35000.0
Oregon        16000.0
Texas         71000.0
Name: population, dtype: float64

发布了36 篇原创文章 · 获赞 58 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/baidu_20183817/article/details/79190040