1.计算布尔值统计信息
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#读取movie,设定行索引是movie_title
pd.options.display.max_columns = 50
movie = pd.read_csv("./data/movie.csv",index_col = 'movie_title')
#判断电影时长是否超过两个小时 #Figure1
movie_2_hours = movie['duration'] > 120
#统计时长超过两小时的电影总数
print(movie_2_hours.sum()) #result:1039
#统计时长超过两小时的电影的比例
print(movie_2_hours.mean())
#统计False和True的比例
print(movie_2_hours.value_counts(normalize = True))
#比较同一个DataFrame中的两列
actors = movie[['actor_1_facebook_likes','actor_2_facebook_likes']].dropna()
print((actors['actor_1_facebook_likes'] > actors['actor_2_facebook_likes']).mean()) #Figure2
运行结果:
Figure1
Figure2
2. 构建多个布尔条件
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#读取movie,设定行索引是movie_title
pd.options.display.max_columns = 50
movie = pd.read_csv("./data/movie.csv",index_col = 'movie_title')
#创建多个布尔条件
criteria1 = movie.imdb_score > 8
criteria2 = movie.content_rating == "PG-13"
criteria3 = (movie.title_year < 2000) | (movie.title_year >= 2010)
"""
print(criteria1.head())
print(criteria2.head())
print(criteria3.head())
运行结果:Figure1
"""
#将多个布尔条件合并成一个
criteria_final = criteria1 & criteria2 & criteria3
print(criteria_final.head())
#运行结果:Figure2
运行结果:
Figure1
Figure2
3.用布尔索引过滤
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#读取movie,设定行索引是movie_title
pd.options.display.max_columns = 50
movie = pd.read_csv("./data/movie.csv",index_col = 'movie_title')
#创建第一个布尔条件
crit_a1 = movie.imdb_score > 8
crit_a2 = movie.content_rating == 'PG-13'
crit_a3 = (movie.title_year < 2000) | (movie.title_year > 2009)
final_crit_a = crit_a1 & crit_a2 & crit_a3
#创建第二个布尔条件
crit_b1 = movie.imdb_score < 5
crit_b2 = movie.content_rating == 'R'
crit_b3 = (movie.title_year >= 2000) & (movie.title_year <= 2010)
final_crit_b = crit_b1 & crit_b2 & crit_b3
#将两个条件用或运算合并起来
final_crit_all = final_crit_a | final_crit_b
print(final_crit_all.head()) #Figure 1
#用最终的布尔条件过滤数据
print(movie[final_crit_all].head()) #Figure2
运行结果:
Figure1
Figure2
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#读取movie,设定行索引是movie_title
pd.options.display.max_columns = 50
movie = pd.read_csv("./data/movie.csv",index_col = 'movie_title')
#创建第一个布尔条件
crit_a1 = movie.imdb_score > 8
crit_a2 = movie.content_rating == 'PG-13'
crit_a3 = (movie.title_year < 2000) | (movie.title_year > 2009)
final_crit_a = crit_a1 & crit_a2 & crit_a3
#创建第二个布尔条件
crit_b1 = movie.imdb_score < 5
crit_b2 = movie.content_rating == 'R'
crit_b3 = (movie.title_year >= 2000) & (movie.title_year <= 2010)
final_crit_b = crit_b1 & crit_b2 & crit_b3
#将两个条件用或运算合并起来
final_crit_all = final_crit_a | final_crit_b
#使用loc,对指定的列做过滤操作,可以清楚地看到过滤是否起作用
cols = ['imdb_score','content_rating','title_year']
movie_filtered = movie.loc[final_crit_all,cols]
print(movie_filtered.head(10))
运行结果:
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦