Pandas-数据的合并和分组聚合

本文介绍了Pandas库在数据处理中的关键操作,包括字符串离散化、数据合并(join和merge)以及数据分组聚合。通过实例展示了如何进行数据的索引操作,如Series和DataFrame的复合索引,并提供了如何使用project进行数据聚合。最后,文章给出了使用matplotlib分析全球星巴克店铺分布和书籍数据的案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串离散化

  • 思路:重新构造一个全为0的数组,列名为分类,如果某一条数据中分类出现过,就让0变为1
import pandas as pd  
from matplotlib import pyplot as plt  
import numpy as np  
  
file_path = "/Users/Downloads/AI_Documents/14100_HM数据科学库课件/DataAnalysis-master/day05/code/IMDB-Movie-Data.csv"  
df = pd.read_csv(file_path)  
print(df["Genre"].head(3))  
  
#统计分类的列表  
temp_list = df["Genre"].str.split(",").tolist()  #[[],[],[]]列表嵌套列表  
print(temp_list)  
genre_list = list(set([i for j in temp_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)  
  
#给每个电影出现分类的位置赋值1  
for i in range(df.shape[0]):  
	zeros_df.loc[i,temp_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,width=0.4,color="orange")  
plt.xticks(range(len(_x)),_x)  
plt.show()

数据合并

join

  • 将行索引相同的数据合并到一起
    df1.join(df2) #以df1为准

merge

  • 以列索引为准
    默认的合并方式inner,交集
    merge outer,并集,NaN补全
    merge left,左边为准,NaN补全
    merge right,右边为准,NaN补全

数据分组聚合

df.groupby(by="columns_name")

project

现在我们有一组关于全球星巴克店铺的统计数据,如果我想知道美国的星巴克数量和中国的哪个多,或者我想知道中国每个省份星巴克的数量的情况,那么应该怎么办?

# coding=utf-8  
import pandas as pd  
import numpy as np  
  
file_path = "/Users/Downloads/AI_Documents/14100_HM数据科学库课件/DataAnalysis-master/day05/code/starbucks_store_worldwide.csv"  
  
df = pd.read_csv(file_path)  
print(df.head(1))  
#print(df.info())  
grouped = df.groupby(by="Country")  
print(grouped)  
  
#调用聚合方法  
country_count = grouped["Brand"].count()  
print(country_count)  
print(country_count["US"])  
print(country_count["CN"])  
  
#统计中国每个省店铺的数量  
china_data = df[df["Country"] =="CN"]  
print(china_data)  
grouped = china_data.groupby(by="State/Province").count()["Brand"]  
print(grouped)  
  
#数据按照多个条件进行分组,返回Series,第一列和第二列都是索引  
grouped = df["Brand"].groupby(by=[df["Country"],df["State/Province"]]).count()  
print(grouped)  
print(type(grouped))  
  
#数据按照多个条件进行分组,返回DataFrame  
grouped1 = df[["Brand"]].groupby(by=[df["Country"],df["State/Province"]]).count()  
# grouped2= df.groupby(by=[df["Country"],df["State/Province"]])[["Brand"]].count()  
# grouped3 = df.groupby(by=[df["Country"],df["State/Province"]]).count()[["Brand"]]  
  
print(grouped1,type(grouped1))  
print("*"*100)  
print(grouped2,type(grouped2))  
print("*"*100)    
print(grouped3,type(grouped3))  
  
#索引的方法和属性  
print(grouped1.index)

数据的索引

索引操作

获取index:df.index

指定index :df.index = ['x','y']

#实则是对dataframe进行取行
重新设置index : df.reindex(list("abcedf")) 

#drop为假表示之前列充当索引的列名称依然保存
指定某一列作为index :df.set_index("Country",drop=False)

返回index的唯一值:df.set_index("Country").index.unique()

Series复合索引

X= a.set_index(["c","d"]) ["a"]  #c为外层索引,d为内层索引
X.swaplevel()["h"]  #level相当于就是复合索引的里外层,交换了level之后,里外交换

DataFrame复合索引

x = a.set_index(["c","d"])[["a"]
x.loc["one"].loc["h"]

project

  1. starbucks
    (1) 使用matplotlib呈现出店铺总数排名前10的国家
import pandas as pd  
from matplotlib import pyplot as plt  
  
file_path = "/Users/Downloads/AI_Documents/14100_HM数据科学库课件/DataAnalysis-master/day05/code/starbucks_store_worldwide.csv"  
  df = pd.read_csv(file_path)  
  
#使用matplotlib呈现出店铺总数排名前10的国家  
#准备数据  
data1 = df.groupby(by="Country").count()["Brand"].sort_values(ascending=False)[:10]  
  
_x = data1.index  
_y = data1.values  
  
#画图  
plt.figure(figsize=(20,8),dpi=80)  
  
plt.bar(range(len(_x)),_y)  
  
plt.xticks(range(len(_x)),_x)  
  
plt.show()

(2)使用matplotlib呈现出每个中国每个城市的店铺数量

import pandas as pd  
from matplotlib import pyplot as plt  
from matplotlib import font_manager  
  
my_font = font_manager.FontProperties(fname="C:\Windows\Fonts\STXINGKA.TTF")  
  
file_path = "F:\学习资料\B站Python教程数据处理\DataAnalysis-master\day05\code\starbucks_store_worldwide.csv"  
  
df = pd.read_csv(file_path)  
df = df[df["Country"]=="CN"]  
  
#使用matplotlib呈现出店铺总数排名前10的国家  
#准备数据  
data1 = df.groupby(by="City").count()["Brand"].sort_values(ascending=False)[:25]  
  
_x = data1.index  
_y = data1.values  
  
#画图  
plt.figure(figsize=(18,15),dpi=100)  
  
# plt.bar(range(len(_x)),_y,width=0.3,color="orange")  
plt.barh(range(len(_x)),_y,height=0.3,color="orange")  
  
plt.yticks(range(len(_x)),_x,fontproperties=my_font)  
  
plt.show()
  1. 现在我们有全球排名靠前的10000本书的数据,那么请统计一下下面几个问题:(1)不同年份书的数量(2)不同年份书的平均评分情况
import pandas as pd  
from matplotlib import pyplot as plt  
  
  
file_path = "./books.csv"  
  
df = pd.read_csv(file_path)  
# print(df.head(2))   
# print(df.info())  
  
# data1 = df[pd.notnull(df["original_publication_year"])]  
# grouped = data1.groupby(by="original_publication_year").count()["title"]  
  
  
#不同年份书的平均评分情况  
#去除original_publication_year列中nan的行  
data1 = df[pd.notnull(df["original_publication_year"])]  
  
grouped = data1["average_rating"].groupby(by=data1["original_publication_year"]).mean()  
  
# print(grouped)  
  
_x = grouped.index  
_y = grouped.values  
  
#画图  
plt.figure(figsize=(20,8),dpi=80)  
plt.plot(range(len(_x)),_y)  
print(len(_x))  
  
plt.xticks(list(range(len(_x)))[::10],_x[::10].astype(int),rotation=45)  
plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值