In [3]:
import pandas as pd
import numpy as np
# 1.通过list创建Series
s1 = pd.Series([1,2,3,4,5])
print(s1)
0 1 1 2 2 3 3 4 4 5 dtype: int64
In [8]:
# 2.通过数组创建Series
arr1 = np.arange(1, 6)
arr1
Out[8]:
array([1, 2, 3, 4, 5])
In [9]:
s2 = pd.Series(arr1)
s2
Out[9]:
0 1 1 2 2 3 3 4 4 5 dtype: int64
In [10]:
s2 = pd.Series(arr1, index=['a','b','c','d','e'])
s2
Out[10]:
a 1 b 2 c 3 d 4 e 5 dtype: int64
In [11]:
s2['c'] += 1
s2
Out[11]:
a 1 b 2 c 4 d 4 e 5 dtype: int64
In [12]:
s2.values
Out[12]:
array([1, 2, 4, 4, 5])
In [13]:
s2.index
Out[13]:
Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
In [14]:
# 3.通过字典创建Series
dict = {'name': '小明', 'age': 21, 'class': '三班'}
s3 = pd.Series(dict, index=['name', 'age', 'class', 'sex'])
s3
Out[14]:
name 小明 age 21 class 三班 sex NaN dtype: object
In [15]:
# 由于数据中没有对应sex的数据,所以创建后的数据中sex为NaN
Series的基本用法¶
isnull和notnull校验缺失值¶
In [16]:
s3.isnull() # 判断是否为空,空就是True
Out[16]:
name False age False class False sex True dtype: bool
In [17]:
s3.notnull() # 判断是否不为空,非空为True
Out[17]:
name True age True class True sex False dtype: bool
通过索引获取数据¶
In [18]:
print(s3.index)
print(s3.values)
Index(['name', 'age', 'class', 'sex'], dtype='object') ['小明' 21 '三班' nan]
In [19]:
# 标签名
s3['age']
Out[19]:
21
In [20]:
# 选取多个
s3[[1,3]]
Out[20]:
age 21 sex NaN dtype: object
In [21]:
# 切片
In [22]:
s3[1:3]
Out[22]:
age 21 class 三班 dtype: object
In [23]:
# 标签切片 包含末端数据
s3['name':'class']
Out[23]:
name 小明 age 21 class 三班 dtype: object
In [25]:
# 布尔索引
s2[s2 > 3]
Out[25]:
c 4 d 4 e 5 dtype: int64
In [27]:
# 索引与数据的对应关系不被运算结果影响
print(s2 * 2)
print(s2 > 2)
a 2 b 4 c 8 d 8 e 10 dtype: int64 a False b False c True d True e True dtype: bool
In [28]:
# name属性
s2.name = 'temp' # 对象名
s2.index.name = 'year' # 对象索引名
s2
Out[28]:
year a 1 b 2 c 4 d 4 e 5 Name: temp, dtype: int64
In [31]:
s2.head() # 默认5行
s2.head(3)
Out[31]:
year a 1 b 2 c 4 Name: temp, dtype: int64
In [32]:
s2.tail()
Out[32]:
year a 1 b 2 c 4 d 4 e 5 Name: temp, dtype: int64