python Pandas中數(shù)據(jù)的合并與分組聚合
作者:沉迷學習的鄭博士
大家好,本篇文章主要講的是python Pandas中數(shù)據(jù)的合并與分組聚合,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下
一、字符串離散化示例
對于一組電影數(shù)據(jù),我們希望統(tǒng)計電影分類情況,應該如何處理數(shù)據(jù)?(每一個電影都有很多個分類)
思路:首先構(gòu)造一個全為0的數(shù)組,列名為分類,如果某一條數(shù)據(jù)中分類出現(xiàn)過,就讓0變?yōu)?
代碼:
# coding=utf-8 import pandas as pd from matplotlib import pyplot as plt import numpy as np file_path = "./IMDB-Movie-Data.csv" df = pd.read_csv(file_path) print(df["Genre"].head(3)) #統(tǒng)計分類的列表 temp_list = df["Genre"].str.split(",").tolist() #[[],[],[]] genre_list = list(set([i for j in temp_list for i in j])) #構(gòu)造全為0的數(shù)組 zeros_df = pd.DataFrame(np.zeros((df.shape[0],len(genre_list))),columns=genre_list) # print(zeros_df) #給每個電影出現(xiàn)分類的位置賦值1 for i in range(df.shape[0]): #zeros_df.loc[0,["Sci-fi","Mucical"]] = 1 zeros_df.loc[i,temp_list[i]] = 1 # print(zeros_df.head(3)) #統(tǒng)計每個分類的電影的數(shù)量和 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="blue") plt.xticks(range(len(_x)),_x) plt.show()
結(jié)果:
二、數(shù)據(jù)合并
2.1 join
join:默認情況下他是把行索引相同的數(shù)據(jù)合并到一起
2.2 merge
merge:按照指定的列把數(shù)據(jù)按照一定的方式合并到一起
三、數(shù)據(jù)的分組和聚合
示例:現(xiàn)在我們有一組關(guān)于全球星巴克的店鋪的統(tǒng)計數(shù)據(jù),如果我想知道美國的星巴克數(shù)量和中國的哪個多,或者我想知道中國每個省份的星巴克的數(shù)量情況,應該怎么辦?
代碼:
import pandas as pd file_path = "./starbucks_store_worldwide.csv" df = pd.read_csv(file_path) grouped = df.groupby(by="Country")#按照分組查詢 # print(grouped) #DataFrameGroupBy #可以進行遍歷 # for i,j in grouped: # print(i) # print("-"*100) # print(j,type(j)) # print("*"*100) # 調(diào)用聚合方法 country_count = grouped["Brand"].count() # print(country_count["US"]) # print(country_count["CN"]) #統(tǒng)計中國每個省店鋪的數(shù)量 china_data = df[df["Country"] =="CN"] grouped = china_data.groupby(by="State/Province").count()["Brand"] # print(grouped) # 數(shù)據(jù)按照多個條件進行分組,返回Series grouped = df["Brand"].groupby(by=[df["Country"],df["State/Province"]]).count() # print(grouped) # print(type(grouped)) # 數(shù)據(jù)按照多個條件進行分組,返回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))
四、索引
簡單的索引操作:
獲取index:df.index
指定index:df.index=['x','y']
重新設置index:df.reindex(list("abcdef"))
指定某一行作為index:df.set_index("Country",drop=False)
返回index的唯一值:df.set_index("Country").index.unique()
總結(jié)
到此這篇關(guān)于python Pandas中數(shù)據(jù)的合并與分組聚合的文章就介紹到這了,更多相關(guān)python Pandas內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!