1.Series的基本属性和方法
-
shape 形状
-
size 长度
-
index 索引
-
values 值
-
name 名字
# 导包
import pandas as pd
s = pd.Series({
"语文":100,
"数学":150,
"英语":110,
"Python":130,
"Pandas":150,
"NumPy":150
},name="考试成绩")
s
# 执行结果
语文 100
数学 150
英语 110
Python 130
Pandas 150
NumPy 150
Name: 考试成绩, dtype: int64
# 形状
s.shape
# 执行结果
(6,)
# 元素个数
s.size
# 执行结果
6
# 索引
s.index
# 执行结果
Index(['语文', '数学', '英语', 'Python', 'Pandas', 'NumPy'], dtype='object')
# 值
s.values
# 执行结果
array([100, 150, 110, 130, 150, 150], dtype=int64)
# 索引名字
s.name
# 执行结果
'考试成绩'
-
head() 查看前几条数据,默认5条
-
tail() 查看后几条数据,默认5条
# 查看前几条数据,默认5条
s.head()
# 执行结果
语文 100
数学 150
英语 110
Python 130
Pandas 150
Name: 考试成绩, dtype: int64
# 查看指定前面2条数据
s.head(2)
# 执行结果
语文 100
数学 150
Name: 考试成绩, dtype: int64
# 查看最后几条数据,默认5条
s.tail()
# 执行结果
数学 150
英语 110
Python 130
Pandas 150
NumPy 150
Name: 考试成绩, dtype: int64
# 查看指定最后2条数据
s.tail(2)
# 执行结果
Pandas 150
NumPy 150
Name: 考试成绩, dtype: int64
2.检测缺失数据
-
pd.isnull()
-
pd.notnull()
-
isnull()
-
notnull()
s = pd.Series(["张三","李四","王五",np.nan])
s
# 执行结果
0 张三
1 李四
2 王五
3 NaN
dtype: object
# isnull:判断是否为空
s.isnull()
# 执行结果
0 False
1 False
2 False
3 True
dtype: bool
pd.isnull(s)
# 执行结果
0 False
1 False
2 False
3 True
dtype: bool
# notnull:判断是否不为空
s.notnull()
# 执行结果
0 True
1 True
2 True
3 False
dtype: bool
pd.notnull(s)
# 执行结果
0 True
1 True
2 True
3 False
dtype: bool
3.使用bool值索引过滤数据
# 第一种方式:过滤掉空值
cond1 = s.isnull()
cond1
# ~ 取反
s[~cond1]
# 执行结果
0 张三
1 李四
2 王五
dtype: object
# 第二种方式:过滤掉空值
cond2 = s.notnull()
cond2
s[cond2]
# 执行结果
0 张三
1 李四
2 王五
dtype: object