pandas.Series(data,index,dtype,copy)
data:支持多种数据类型
index:索引值必须是唯一的,与data的长度相同
dtype:数据类型
copy:是否复制数据
- ndarray创建一个Series对象
import pandas as pd import numpy as np data=np.array(['a','b','c','d']) s=pd.Series(data,index=[100,101,102,103]) print(s)
输出结果为:100 a
101 b
102 c
103 d
dtype:object
- 字典创建一个Series
#不传递index的话,key为index,value为传入的值
import pandas as pd
import numpy as np
data={'a':0.,'b':1.,'c':2.}
s=pd.Series(data)
print(s)
输出结果为:a 0.0
b 1.0
c 2.0
dtype:float64
#传入index的话,先根据index匹配key,key中不存在的index的值为NaN
- 从常量创建一个Series
import pandas as pd import numpy as np s=pd.Series(5,index=[1,2,3,4]) print(s)
输出结果为:
1 5
2 5
3 5
4 5
dtype:int64
访问Series数据,如下列代码行
import pandas as pd s=pd.Series([1,2,3,4,5],index=['a','b','c','d','e']) #通过位置访问数据 print(s[0]) #检索第一个元素 # 1 print(s[:3]) #检索s中的前三个元素 '''a 1 b 2 c 3 dtype:int64''' print(s[-3:]) '''c 3 d 4 e 5 dtype:int64''' #通过索引访问数据 print(s['a']) # 1 print(s[['a','c','d']]) '''a 1 c 3 d 4 dtype:int64''' #如果Series中没有此索引,则返回KeyError错误,如下: print(s['f'])
- Series对象的使用
1.axes:返回Series索引列表
2.dtype:返回Series的数据类型
3.empty:判断Series是否为空,如果为空,则返回true
4.ndim:返回基础数据的维度数,默认为:1
5.size:返回基础数据中的元素个数
6.values:将Series作为ndarray返回
7.head():返回前n行
8.tail():返回最后n行
import numpy as np import pandas as pd s=pd.Series(np.array([1,2,3,4])) print(s) ''' 0 1 1 2 2 3 3 4''' print(s.axes) #[RangeIndex(start=0,stop=0,step=1)] print(s.dtype) #int32 print(s.empty) #false print(s.nidm) # 1 print(s.size) # 4 print(s.values) #[1 2 3 4] print(s.head(2)) '''0 1 1 2 dtype=int32''' print(s.tail(2)) '''2 3 3 4 dtype:int32'''
- 以上就是关于pandas模块中Series对象的一些简易操作,望大家在继续学习的路上,能够越来越棒!



