#案例1-复习字符串离散化,合并,进行新学习-分组
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
file = "文件所在位置IMDB-Movie-Data.csv"
df = pd.read_csv(file)
print(df.head(1))
print(df["Genre"]) # 分类
# 统计分类的列表
a_list = df["Genre"].str.split(",").tolist() # [[],[],[]]
print(a_list)
genre_list = list(set([i for j in a_list for i in j]))
print(genre_list)
# 构造全为0的数组
zeros_df = pd.DataFrame(np.zeros((df.shape[0],len(genre_list))), columns=genre_list)
print(zeros_df)
#给每个电影出现分类的位置赋值
for i in range(df.shape[0]):
#zeros_df.loc[0,["sci-fi","mucical"]]=1
zeros_df.loc[i,a_list[i]] =1
print(zeros_df.head(3))
#统计每个分类电影的数量和
genre_count = zeros_df.sum(axis=0)
print(genre_count)
#排序
genre_count=genre_count.sort_values()
_x =genre_count.index
_y =genre_count.values
#画图
plt.figure(figsize=(20,8),dpi=80)
plt.bar(range(len(_x)),_y)
plt.xticks(range(len(_x)),_y)
plt.show()
###数组合并join/2 按照列索引进行操作 index
import numpy as np
import pandas as pd
df1 = pd.DataFrame(np.ones((2,4)),index=["A","B"],columns= list("abcd"))
print(df1)
df2 = pd.DataFrame(np.zeros((3,3)),index=["A","B","C"],columns= list("XYZ"))
print(df2)
df1.join(df2) #以df1为主
df2.join(df1)
##merge 取并集 按照行索引进操作 column
df3 = pd.DataFrame(np.zeros((3,3)),columns= list("fax"))
print(df3)
df1.merge(df3,on="a")
df1.merge(df3)
df3.loc[1,"a"] =1 #a 列的第一行取值为1
print(df3)
df1.merge(df3,on="a")
df1.merge(df3,on="a",how="outer")
df1.merge(df3,on="a",how="left") #以df1为准
df1.merge(df3,on="a",how="right") #以df3为准
##全球星巴克的统计数据,中国每个省份的数量?
import numpy as np
import pandas as pd
file = ""文件所在位置IMDB-Movie-Data.csvstarbucks_store_worldwide.csv"
df = pd.read_csv(file)
print(df.head(1))
print(df.info())
##分组操作
grouped = df.groupby(by="Country")
print(grouped)
# Datafarm groupedby 可以进行遍历
for i,j in grouped:
print(i)
print("_" * 100)
print(j, type(j))
print("*" * 100)
us = df[df["Country"] == "US"] #调用英国数据
print(us)
##调用聚合方法
print(grouped.count()) ##统计个数
count_1 = grouped["Brand"].count()
print(count_1)
print(count_1["US"])
print(count_1["CN"])
#中国每个省份的数量
china_data = df[df["Country"] == "CN"] #调用英国数据
print(china_data)
grouped = china_data.groupby(by="State/Province").count()["Brand"]
print(grouped)
##.从pandas DataFrame列标题中获取列表名
df.columns
list(df)
df.keys()
##对国家和省份进行分组统计
grouped2 = df.groupby(by=[df["Country"],df["State/Province"]])
print(grouped2)
##获取分许后的某一部分数据
grouped1 =df.groupby(by=[df["Country"],"State/Province"])["Country"].count()
print(grouped1)
##对某几列数据进行分组
grouped2 = df["Country"].groupby(by=[df["Country"],df["State/Province"]]).count()
print(grouped2)
##数据按照多个条件(一个是国家,一个是省市)进行分组
grouped3 = df["Brand"].groupby(by=[df["Country"],df["State/Province"]]).count()
print(grouped3)
print(type(grouped3)) #两个索引 一个是国家,一个是省市
##返回dataframe [[]]- 方括号嵌套方括号
grouped4 = df["Brand"].groupby(by=[df["Country"],df["State/Province"]]).count()
grouped5 = df.groupby(by=[df["Country"],df["State/Province"]])[["Brand"]].count()
grouped6 = df.groupby(by=[df["Country"],df["State/Province"]]).count()[["Brand"]]
print(grouped4)
print("*"*100)
print(grouped5)
print("*"*100)
print(grouped6)
案列2
##索引和复合索引
##索引的方法和属性
print(grouped4.index)
import pandas as pd
a = pd.DataFrame({"a":range(7),"b":range(7,0,-1),"c":["one","one","one","two","two","two","two"],"d":list("hjklmno")})
print(a)
d =a.set_index(["d","c"])["a"]
print(d)
d.swaplevel() #c和d序列交换位置
d.swaplevel()["one"]
a.loc["one"].loc["h"]
#店铺总数排名前十的国家
import pandas as pd
import matplotlib.pyplot as plt
file = "F:/研究方向/6-软件操作/python/python-操作/12-人工智能阶段-数据分析/数据分析资料/day05/code/starbucks_store_worldwide.csv"
df = pd.read_csv(file)
print(df.head(1))
print(df.info())
#准备数据
#取前店铺总数排名前10的国家
data = df.groupby(by="Country").count()["Brand"].sort_values(ascending=False)[:10]
_x=data.index
_y=data.values
##画图
plt.figure(figsize=(28,8),dpi=88)
plt.bar(range(len(_x)),_y)
plt.xticks(range(len(_x)),_x)
plt.show()
##中国店铺
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties # 字体管理器
# 设置汉字格式
font = FontProperties(fname=r"c:windowsfontssimsun.ttc", size=15)
file = "F:/研究方向/6-软件操作/python/python-操作/12-人工智能阶段-数据分析/数据分析资料/day05/code/starbucks_store_worldwide.csv"
df = pd.read_csv(file)
df = df[df["Country"]=="CN"]
print(df.head(1))
print(df.info())
data = df.groupby(by="City").count()["Brand"].sort_values(ascending=False)[:10]
_x=data.index
_y=data.values
##画图
plt.figure(figsize=(28,8),dpi=88)
#plt.bar(range(len(_x)),_y)
plt.barh(range(len(_x)),_y,height=0.3)
plt.xticks(range(len(_x)),_x,fontproperties=font)
plt.yticks(range(len(_x)),_x,fontproperties=font)
plt.show()
###
import pandas as pd
import matplotlib.pyplot as plt
file = "文件所在位置IMDB-Movie-Data.csvbooks.csv"
df = pd.read_csv(file)
#print(df.head(2))
print(df.info)
#删除1
df.dropna()
##2
#data_1 = df[pd.notnull(df["original_publication_year"])]
#grouprs = data_1.groupby(by="original_publication_year").count()["title"]
#print(grouprs)
#不同年份数的平均评分情况
#1.去除"original_publication_year"的行
data_1 = df[pd.notnull(df["original_publication_year"])]
grouped = data_1["average_rating"].groupby(by=data_1["original_publication_year"]).mean()
print(grouped)
_x=grouped.index
_y=grouped.values
plt.figure(figsize=(28,8),dpi=88)
plt.plot(range(len(_x)),_y)
#取步长 .astype(int)将小数替换为整数
plt.xticks(list(range(len(_x)))[::10],_x[::10].astype(int),rotation=98)
plt.show()