对非数值型的数据进行存储和运算操作
# 将列表作为数据源 Series(data=[1,2,3,4,5]) 0 1 1 2 2 3 3 4 4 5 dtype: int64 # 将字典作为数据源 dic = { ‘A‘: 100, ‘B‘: 99, ‘C‘: 150, } Series(data=dic) A 100 B 99 C 150 dtype: int64 # 将numpy数组作为数据源 Series(np.random.randint(0,100,size=(3,4))) # 上面这样会报错,Series只能存一维的数据 Series(np.random.randint(0,100,size=(3,))) 0 97 1 75 2 78 dtype: int32
# 加上index参数就可以将索引设为显式索引 Series(data=np.random.randint(0,100,size=(3,)), index=[‘A‘,‘B‘,‘C‘]) A 3 B 22 C 63 dtype: int32
s = Series(data=np.linspace(0,30, num=5),index=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘]) a 0.0 b 7.5 c 15.0 d 22.5 e 30.0 dtype: float64 # 索引取值 s[1] # 7.5 # 隐式索引 s[‘c‘] # 15.0 #显式索引 s.d # 22.5 #显式索引 # 切片 s[0:3] # 隐式索引 a 0.0 b 7.5 c 15.0 dtype: float64 s[‘a‘:‘d‘] #显式索引 a 0.0 b 7.5 c 15.0 d 22.5 dtype: float64
s.shape # 形状 (5,) s.size # 元素个数 5 s.index # 索引 有显式就是显式索引 Index([‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘], dtype=‘object‘) s.values # 值 array([ 0. , 7.5, 15. , 22.5, 30. ])
# 索引一致的元素进行算数运算否则补空 s1 = Series(data=[1,2,3,4,5],index=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘]) s2 = Series(data=[1,2,3,4,5],index=[‘a‘,‘b‘,‘f‘,‘d‘,‘e‘]) s = s1+s2 a 2.0 b 4.0 c NaN d 8.0 e 10.0 f NaN dtype: float64
s = Series(data=np.linspace(0,30, num=5),index=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘]) a 0.0 b 7.5 c 15.0 d 22.5 e 30.0 dtype: float64 s.head(3) # 只显示前三个 #不写默认值是5 a 0.0 b 7.5 c 15.0 dtype: float64 s.tail(2) # 只显示后俩个 d 22.5 e 30.0 dtype: float64 s=Series(data=[1,2,2,4,4,4,4,5,6,3,3,4,5,3,6,1,3]) s.unique() # 去掉重复元素 array([1, 2, 4, 5, 6, 3], dtype=int64) s.nunique() # 统计去重后的元素个数 6 s1 = Series(data=[1,2,3,4,5],index=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘]) s2 = Series(data=[1,2,3,4,5],index=[‘a‘,‘b‘,‘f‘,‘d‘,‘e‘]) s = s1+s2 s a 2.0 b 4.0 c NaN d 8.0 e 10.0 f NaN dtype: float64 s.isnull() # 检测Series哪些元素为空,为空则返回True,否则返回Fasle a False b False c True d False e False f True dtype: bool s.notnull() # 检测Series哪些元素非空,非空则返回True,否则返回Fasle a True b True c False d True e True f False dtype: bool # 想要将s中的非空的数据取出 s[[True,True,False,True,True,False]] #布尔值可以作为索引去取值 a 2.0 b 4.0 d 8.0 e 10.0 dtype: float64 # 直接将s.notnull()得到的布尔值作为索引取值,可以对Series中空值进行清洗 s[s.notnull()] a 2.0 b 4.0 d 8.0 e 10.0 dtype: float64
原文:https://www.cnblogs.com/wgwg/p/13295033.html