使用pandas处理数据

使用pandas处理大型数据方法来统计数据

下图为使用爬虫爬取豆瓣美国英国中国的电视剧信息
使用pandas处理数据
要求获得每一个国家的电视剧数量,因此需要数据分析,使用pandas方法进行处理,思路为构造一个全为0的数组,然后循环遍历,将属于每一个类别的电影设为1
import pandas as pd

df = pd.read_csv(.//douban.csv) #pandas方法读取csv文件也可是txt或别的
temp_list = df[“country”].tolist() # 每个电影的国家列表
country_list = list(set([i for i in temp_list])) # 总共有的电影分类
zeros_df = pd.DataFrame(np.zeros((df.shape[0], len(country_list))), columns=country_list) # 构造一个全为0的数组
使用pandas处理数据
#遍历每一个电影 数据过多的时候速度很慢,当数据多达几万几十万时不推荐该方法
for country in country_list:
zeros_df[country].str.contains(country)] = 1
print(zeros_df)

#或者遍历三个国家 速度很快
for i in range(df.shape[0]): # 给每个电影出现的分类赋值1
zeros_df.loc[i, temp_list[i]] = 1
print(zeros_df)
使用pandas处理数据

按行统计每个国家电影的数目axis=0是跨行统计 axis=1是跨列进行统计

counts = zeros_df.sum(axis=0)
print(counts)
使用pandas处理数据
绘制条形图
_x = counts.index x轴
_y = counts.values y轴
plt.figure(figsize=(20, 8), dpi=80) 设置图形大小
plt.bar(range(len(_x)), _y, width=0.3, color=“orange”) 设置条形图
plt.xticks(range(len(_x)), _x) 设置x轴刻度
plt.show()
使用pandas处理数据