pandas入门之Series

一、创建Series 

参数

- Series (Series)是能够保存任何类型的数据(整数,字符串,浮点数,Python对象等)的一维标记数组。轴标签统称为索引。
- data 参数
- index 索引 索引值必须是唯一的和散列的,与数据的长度相同。 默认np.arange(n)如果没有索引被传递。
- dtype 输出的数据类型 如果没有,将推断数据类型
- copy 复制数据 默认为false

数组创建

data = ['a','b','c','d','e']
res= pd.Series(data,index=[i for i in range(1,6)],dtype=str)
print(res)

1    a
2    b
3    c
4    d
5    e
dtype: object

字典创建

data = {"a":1.,"b":2,"c":3,"d":4}
res = pd.Series(data,index=["d","c","b","a"])
print(res)        # 字典的键用于构建索引

d    4.0
c    3.0
b    2.0
a    1.0
dtype: float64

常量创建

# 如果数据是常量值,则必须提供索引。将重复该值以匹配索引的长度。
res = pd.Series(5,index=[1,2,3,4,5])
print(res)   

1    5
2    5
3    5
4    5
5    5
dtype: int64

二、数据查询

切片

data = [1,2,3,4,5]
res = pd.Series(data,index=["a","b","c","d","e"])
print(res[0:3],"---")  # 这里跟python的切片一样
print(res[3],"---")
print(res[-3:],"---")

a    1
b    2
c    3
dtype: int64 ---

4 ---

c    3
d    4
e    5
dtype: int64 ---

使用索引检索数据

data = [1,2,3,4,5]
res = pd.Series(data,index=["a","b","c","d","e"])
print(res["a"])
# 检索多个值 标签用中括号包裹
print(res[["a","b"]]) # 如果用没有的标签检索则会抛出异常KeyError: 'f'

1

a    1
b    2
dtype: int64
data = [1,2,3,4,5]
res = pd.Series(data)
res[[2,4]]

2    3
4    5
dtype: int64

使用head()/tail()查看前几个或后几个

data = [1,2,3,4,5]
res = pd.Series(data,index=["a","b","c","d","e"])
res.head(3)  # 查看前三个
res.tail(2)  # 查看后两个

三、其他操作

series元素进行去重

unique() 对series元素进行去重

s = pd.Series(data=[1,1,2,2,3,4,5,6,6,6,7,6,6,7,8])
s.unique()

array([1, 2, 3, 4, 5, 6, 7, 8], dtype=int64)

两个series元素相加

Series之间的运算

- 在运算中自动对齐不同索引的数据
- 如果索引不对应,则补NaN

# 当索引没有对应的值时,可能出现缺失数据显示NaN(not a number)的情况
s1 = pd.Series(data=[1,2,3,4,5],index=["a","b","c","d","e"])
s2 = pd.Series(data=[1,2,3,4,5],index=["a","b","c","d","f"])
s = s1 + s2
s

a    2.0
b    4.0
c    6.0
d    8.0
e    NaN
f    NaN
dtype: float64

监测缺失的数据

isnull()  # 缺失的数据返回的布尔值为True
notnull() # 缺失的数据返回的布尔值为False

isnull

s1 = pd.Series(data=[1,2,3,4,5],index=["a","b","c","d","e"])
s2 = pd.Series(data=[1,2,3,4,5],index=["a","b","c","d","f"])
s = s1 + s2
s.isnull()  # 缺失的数据返回的布尔值为True

a    False
b    False
c    False
d    False
e     True
f     True
dtype: bool

notnull

s1 = pd.Series(data=[1,2,3,4,5],index=["a","b","c","d","e"])
s2 = pd.Series(data=[1,2,3,4,5],index=["a","b","c","d","f"])
s = s1 + s2
s.notnull()  # 缺失的数据返回的布尔值为False

a     True
b     True
c     True
d     True
e    False
f    False
dtype: bool

如果将布尔值作为Serrise的索引,则只保留True对应的元素值

s[[True,True,False,False,True,True]] 

a    2.0
b    4.0
e    NaN
f    NaN
dtype: float64

根据上面的特性,可以取出所有空的数据和所有不为空的数据

s[s.isnull()]   # 取所有空值

e   NaN
f   NaN
dtype: float64

s[s.notnull()]  # 取出不为空的数据

a    2.0
b    4.0
c    6.0
d    8.0
dtype: float64


s.index  # 取出索引

Index(['a', 'b', 'c', 'd', 'e', 'f'], dtype='object')

 

posted @ 2019-08-25 14:57  叫我大表哥  阅读(15411)  评论(0编辑  收藏  举报