数据分析之Series基本操作

导入包

import numpy as np
import pandas as pd
from pandas import Series,DataFrame

Series是一种类似与一维数组的对象,由下面两个部分组成:

  • values:一组数据(ndarray类型)
  • index:相关的数据索引标签
  • 由列表或numpy数组创建
  • 默认索引为0到N-1的整数型索引
s=Series(data=[1,2,5,4,7])
s
0    1
1    2
2    5
3    4
4    7
dtype: int64
s1=Series(data=np.random.randint(1,100,5))
s1
0     7
1    50
2    24
3    81
4    49
dtype: int32

指定行索引

s=Series(data=[1,2,5,4,7],index=['A','B','C','D','E'])
s
A    1
B    2
C    5
D    4
E    7
dtype: int64

使用字典创建

dict={
    '语文':88,
    '数学':99,
    '英语':100
}
s2=Series(data=dict)
s2
数学     99
英语    100
语文     88
dtype: int64

Series的索引和切片

可以使用中括号取单个索引(此时返回的是元素类型),或者中括号里一个列表取多个索引(此时返回的是一个Series类型)。分为显示索引和隐式索引:

  • 显式索引:
    使用index中的元素作为索引值
    使用s.loc[](推荐):注意,loc中括号中放置的一定是显示索引
    注意,此时是闭区间
s2
数学     99
英语    100
语文     88
dtype: int64

数学
s2['数学']
99

s2.loc['语文']
88
  • 隐式索引:
    使用整数作为索引值
    使用.iloc[](推荐):iloc中的中括号中必须放置隐式索引 ——注意,此时是半开区间
s2[0]
99

s2[[1,2]]
英语    100
语文     88
dtype: int64
  • 切片:隐式索引切片和显示索引切片¶
    显示索引切片:index和loc
s2.loc['数学':'语文']
数学     99
英语    100
语文     88
dtype: int64
  • 隐式索引切片:整数索引值和iloc
s2[0:3]
数学     99
英语    100
语文     88
dtype: int64
  • 可以使用s.head(),tail()分别查看前n个和后n个值
s2.head(2)
数学     99
英语    100
dtype: int64

s2.tail(2)
英语    100
语文     88
dtype: int64
  • 当索引没有对应的值时,可能出现缺失数据显示NaN(not a number)的情况
    可以使用pd.isnull(),pd.notnull(),或s.isnull(),notnull()函数检测缺失数据
    Series之间的运算+ - * /, add() sub() mul() div() : s1.add(s2,fill_value=0)
    在运算中自动对齐不同索引的数据
    如果索引不对应,则补NaN
ks2+2
数学    101
英语    102
语文     90
dtype: int64

s1+s2
0    NaN
1    NaN
2    NaN
3    NaN
4    NaN
数学   NaN
英语   NaN
语文   NaN
dtype: float64

猜你喜欢

转载自blog.csdn.net/qq_42055440/article/details/81146003