赞
踩
import pandas as pd
# 假设有 5 个人,分别参加了 2 门课程,获得了对应的分数
data = {'name' : pd.Series(['Alice', 'Bob', 'Cathy', 'Dany', 'Ella']),
'Math' : pd.Series([1.1, 2.2, 3.3, 4.4, 5]),
'English' : pd.Series([3, 2.6, 2, 1.7, 3])
}
df = pd.DataFrame(data)
print(df)
运行结果:
name Math English
0 Alice 1.1 3.0
1 Bob 2.2 2.6
2 Cathy 3.3 2.0
3 Dany 4.4 1.7
4 Ella 5.0 3.0
print(df[df.Math > 2.5]) # 筛选 'Math' 这门课分数高于 2.5 分的 行
运行结果:
name Math English
2 Cathy 3.3 2.0
3 Dany 4.4 1.7
4 Ella 5.0 3.0
逻辑运算表:
(仅限于行之间的重复:同一列,不同行的数值相同)
print(df.drop_duplicates(subset='English')) # 删除 'English' 这门课 分数 一样 的 行
运行结果:
name Math English
0 Alice 1.1 3.0
1 Bob 2.2 2.6
2 Cathy 3.3 2.0
3 Dany 4.4 1.7
print(df.head(2)) # 显示前面 2 行
运行结果:
name Math English
0 Alice 1.1 3.0
1 Bob 2.2 2.6
print(df.tail(2)) # 显示后面 2 行
运行结果:
name Math English
3 Dany 4.4 1.7
4 Ella 5.0 3.0
print(df.sample(frac=0.2)) # 这里一共 5 行,5*0.2 = 1 行
运行结果:
name Math English
4 Ella 5.0 3.0
print(df.sample(n=2)) # 随机抽取 2 行
运行结果:
name Math English
3 Dany 4.4 1.7
2 Cathy 3.3 2.0
# 选取第 2~3 行(从 0 行开始)
print(df.iloc[2:4]) # 切片操作,需要注意的是后面的数字是 4 , 第 4 行不取
运行结果:
name Math English
2 Cathy 3.3 2.0
3 Dany 4.4 1.7
print(df.nlargest(3,'Math')) # 从大到小排序,并取得 'Math' 最大的 3 行
运行结果:
name Math English
4 Ella 5.0 3.0
3 Dany 4.4 1.7
2 Cathy 3.3 2.0
print(df.nsmallest(3,'Math')) # 从大到小排序,并取得 'Math' 最大的 3 行
运行结果:
name Math English
0 Alice 1.1 3.0
1 Bob 2.2 2.6
2 Cathy 3.3 2.0
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。