本文用到的表格内容如下:
先来看一下原始情形:
import pandas as pd
df = pd.read_excel(r'C:\Users\admin\Desktop\测试.xlsx')
print(df)
result:
分类 货品 销售量 价钱
0 水果 苹果 34 12
1 家电 电视机 56 3498
2 家电 冰箱 78 2578
3 书籍 python从入门到放弃 25 78
4 水果 葡萄 789 7
1.数值计数
数值计数,主要用到value_counts()方法
1.1统计某一列每个值的出现次数
import pandas as pd
df = pd.read_excel(r'C:\Users\admin\Desktop\测试.xlsx')
print(df['分类'].value_counts())
result:
水果 2
家电 2
书籍 1
Name: 分类, dtype: int64
结果表明,分类为水果的记录有2条, 分类为家电的记录有2条,分类为书籍的记录有1条。
1.2统计某一列每个值的出现占比
df = pd.read_excel(r'C:\Users\admin\Desktop\测试.xlsx')
print(df['分类'].value_counts(normalize=True))
result:
水果 0.4
家电 0.4
书籍 0.2
Name: 分类, dtype: float64
结合1.1来看,水果的占比2/(2+2+1)=0.4,其余依次类推
2.数值查找
数值查找就是查看数据表中的数据是否包含某个值或者某些值
主要使用到的方法是isin()方法,如果包含返回True,否则返回False
2.1在某一列查找
2.1.1查找单个值
import pandas as pd
df = pd.read_excel(r'C:\Users\admin\Desktop\测试.xlsx')
print(df['分类'].isin(["水果"]))
result:
0 True
1 False
2 False
3 False
4 True
Name: 分类, dtype: bool
分类这一列、第一行和第5行的值为水果,所以对应的值为True,其他行的值为False
注:不支持模糊查找
df = pd.read_excel(r'C:\Users\admin\Desktop\测试.xlsx')
print(df['分类'].isin(["果"]))
result:
0 False
1 False
2 False
3 False
4 False
Name: 分类, dtype: bool
2.1.2查找多个值
df = pd.read_excel(r'C:\Users\admin\Desktop\测试.xlsx')
print(df['分类'].isin(["水果", "家电"]))
result:
0 True
1 True
2 True
3 False
4 True
Name: 分类, dtype: bool
2.2 全表查找
2.2.1查找单个值
df = pd.read_excel(r'C:\Users\admin\Desktop\测试.xlsx')
print(df.isin(["水果"]))
result:
分类 货品 销售量 价钱
0 True False False False
1 False False False False
2 False False False False
3 False False False False
4 True False False False
分类这一列、第一行和第5行的值为水果,所以对应的值为True,其他行的值为False
注:同样地,全表查找也不支持模糊查找
df = pd.read_excel(r'C:\Users\admin\Desktop\测试.xlsx')
print(df['分类'].isin(["果"]))
result:
分类 货品 销售量 价钱
0 False False False False
1 False False False False
2 False False False False
3 False False False False
4 False False False False
2.2.2查找多个值
df = pd.read_excel(r'C:\Users\admin\Desktop\测试.xlsx')
print(df.isin(["水果", "家电", "苹果"]))
result:
0 True
1 True
2 分类 货品 销售量 价钱
0 True True False False
1 True False False False
2 True False False False
3 False False False False
4 True False False FalseTrue
3 False
4 True
Name: 分类, dtype: bool