电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

Python pandas軸旋轉stack和unstack的使用說明

瀏覽:8日期:2022-06-26 11:12:54

摘要

前面給大家分享了pandas做數據合并的兩篇[pandas.merge]和[pandas.cancat]的用法。今天這篇主要講的是pandas的DataFrame的軸旋轉操作,stack和unstack的用法。

首先,要知道以下五點:

1.stack:將數據的列“旋轉”為行

2.unstack:將數據的行“旋轉”為列

3.stack和unstack默認操作為最內層

4.stack和unstack默認旋轉軸的級別將會成果結果中的最低級別(最內層)

5.stack和unstack為一組逆運算操作

第一點和第二點以及第五點比較好懂,可能乍看第三點和第四點會不太理解,沒關系,看看具體下面的例子,你就懂了。

1、創建DataFrame,行索引名為state,列索引名為number

import pandas as pdimport numpy as npdata = pd.DataFrame(np.arange(6).reshape((2,3)),index=pd.Index([’Ohio’,’Colorado’],name=’state’) ,columns=pd.Index([’one’,’two’,’three’],name=’number’))data

Python pandas軸旋轉stack和unstack的使用說明

2、將DataFrame的列旋轉為行,即stack操作

result = data.stack()result

Python pandas軸旋轉stack和unstack的使用說明

從下圖中結果來理解上述點4,stack操作后將列索引number旋轉為行索引,并且置于行索引的最內層(外層為索引state),也就是將旋轉軸(number)的結果置于 最低級別。

3、將DataFrame的行旋轉為列,即unstack操作

result.unstack()

Python pandas軸旋轉stack和unstack的使用說明

從下面結果理解上述點3,unstack操作默認將內層索引number旋轉為列索引。

同時,也可以指定分層級別或者索引名稱來指定操作級別,下面做錯同樣會得到上面的結果。

Python pandas軸旋轉stack和unstack的使用說明

4、stack和unstack逆運算

s1 = pd.Series([0,1,2,3],index=list(’abcd’))s2 = pd.Series([4,5,6],index=list(’cde’))data2 = pd.concat([s1,s2],keys=[’one’,’two’])data2

Python pandas軸旋轉stack和unstack的使用說明

data2.unstack().stack()

Python pandas軸旋轉stack和unstack的使用說明

補充:使用Pivot、Pivot_Table、Stack和Unstack等方法在Pandas中對數據變形(重塑)

Pandas是著名的Python數據分析包,這使它更容易讀取和轉換數據。在Pandas中數據變形意味著轉換表或向量(即DataFrame或Series)的結構,使其進一步適合做其他分析。在本文中,小編將舉例說明最常見的一些Pandas重塑功能。

一、Pivot

pivot函數用于從給定的表中創建出新的派生表,pivot有三個參數:索引、列和值。具體如下:

def pivot_simple(index, columns, values): ''' Produce ’pivot’ table based on 3 columns of this DataFrame. Uses unique values from index / columns and fills with values. Parameters ---------- index : ndarray Labels to use to make new frame’s index columns : ndarray Labels to use to make new frame’s columns values : ndarray Values to use for populating new frame’s values

作為這些參數的值需要事先在原始的表中指定好對應的列名。然后,pivot函數將創建一個新表,其行和列索引是相應參數的唯一值。我們一起來看一下下面這個例子:

假設我們有以下數據:

Python pandas軸旋轉stack和unstack的使用說明

我們將數據讀取進來:

from collections import OrderedDictfrom pandas import DataFrameimport pandas as pdimport numpy as np data = OrderedDict(( ('item', [’Item1’, ’Item1’, ’Item2’, ’Item2’]), (’color’, [’red’, ’blue’, ’red’, ’black’]), (’user’, [’1’, ’2’, ’3’, ’4’]), (’bm’, [’1’, ’2’, ’3’, ’4’])))data = DataFrame(data)print(data)

得到結果為:

item color user bm0 Item1 red 1 11 Item1 blue 2 22 Item2 red 3 33 Item2 black 4 4

接下來,我們對以上數據進行變形:

df = data.pivot(index=’item’, columns=’color’, values=’user’)print(df)

得到的結果為:

color black blue reditem Item1 None 2 1Item2 4 None 3

注意:可以使用以下方法對原始數據和轉換后的數據進行等效查詢:

# 原始數據集print(data[(data.item==’Item1’) & (data.color==’red’)].user.values) # 變換后的數據集print(df[df.index==’Item1’].red.values)

結果為:

[’1’][’1’]

在以上的示例中,轉化后的數據不包含bm的信息,它僅包含我們在pivot方法中指定列的信息。下面我們對上面的例子進行擴展,使其在包含user信息的同時也包含bm信息。

df2 = data.pivot(index=’item’, columns=’color’)print(df2)

結果為:

user bm color black blue red black blue reditem Item1 None 2 1 None 2 1Item2 4 None 3 4 None 3

從結果中我們可以看出:Pandas為新表創建了分層列索引。我們可以用這些分層列索引來過濾出單個列的值,例如:使用df2.user可以得到user列中的值。

二、Pivot Table

有如下例子:

data = OrderedDict(( ('item', [’Item1’, ’Item1’, ’Item1’, ’Item2’]), (’color’, [’red’, ’blue’, ’red’, ’black’]), (’user’, [’1’, ’2’, ’3’, ’4’]), (’bm’, [’1’, ’2’, ’3’, ’4’])))data = DataFrame(data) df = data.pivot(index=’item’, columns=’color’, values=’user’)

得到的結果為:

ValueError: Index contains duplicate entries, cannot reshape

因此,在調用pivot函數之前,我們必須確保我們指定的列和行沒有重復的數據。如果我們無法確保這一點,我們可以使用pivot_table這個方法。

pivot_table方法實現了類似pivot方法的功能,它可以在指定的列和行有重復的情況下使用,我們可以使用均值、中值或其他的聚合函數來計算重復條目中的單個值。

首先,我們先來看一下pivot_table()這個方法:

def pivot_table(data, values=None, index=None, columns=None, aggfunc=’mean’,fill_value=None, margins=False, dropna=True,margins_name=’All’): ''' Create a spreadsheet-style pivot table as a DataFrame. The levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame Parameters ---------- data : DataFrame values : column to aggregate, optional index : column, Grouper, array, or list of the previous If an array is passed, it must be the same length as the data. The list can contain any of the other types (except list). Keys to group by on the pivot table index. If an array is passed, it is being used as the same manner as column values. columns : column, Grouper, array, or list of the previous If an array is passed, it must be the same length as the data. The list can contain any of the other types (except list). Keys to group by on the pivot table column. If an array is passed, it is being used as the same manner as column values. aggfunc : function or list of functions, default numpy.mean If list of functions passed, the resulting pivot table will have hierarchical columns whose top level are the function names (inferred from the function objects themselves) fill_value : scalar, default None Value to replace missing values with margins : boolean, default False Add all row / columns (e.g. for subtotal / grand totals) dropna : boolean, default True Do not include columns whose entries are all NaN margins_name : string, default ’All’ Name of the row / column that will contain the totals when margins is True. 接下來我們來看一個示例:data = OrderedDict(( ('item', [’Item1’, ’Item1’, ’Item1’, ’Item2’]), (’color’, [’red’, ’blue’, ’red’, ’black’]), (’user’, [’1’, ’2’, ’3’, ’4’]), (’bm’, [’1’, ’2’, ’3’, ’4’])))data = DataFrame(data) df = data.pivot_table(index=’item’, columns=’color’, values=’user’, aggfunc=np.min)print(df)

結果為:

color black blue reditem Item1 None 2 1Item2 4 None None

實際上,pivot_table()是pivot()的泛化,它允許在數據集中聚合具有相同目標的多個值。

三、Stack/Unstack

事實上,變換一個表只是堆疊DataFrame的一種特殊情況,假設我們有一個在行列上有多個索引的DataFrame。堆疊DataFrame意味著移動最里面的列索引成為最里面的行索引,反向操作稱之為取消堆疊,意味著將最里面的行索引移動為最里面的列索引。例如:

from pandas import DataFrameimport pandas as pdimport numpy as np # 建立多個行索引row_idx_arr = list(zip([’r0’, ’r0’], [’r-00’, ’r-01’]))row_idx = pd.MultiIndex.from_tuples(row_idx_arr) # 建立多個列索引col_idx_arr = list(zip([’c0’, ’c0’, ’c1’], [’c-00’, ’c-01’, ’c-10’]))col_idx = pd.MultiIndex.from_tuples(col_idx_arr) # 創建DataFramed = DataFrame(np.arange(6).reshape(2,3), index=row_idx, columns=col_idx)d = d.applymap(lambda x: (x // 3, x % 3)) # Stack/Unstacks = d.stack()u = d.unstack()print(s)print(u)

得到的結果為:

c0 c1r0 r-00 c-00 (0, 0) NaN c-01 (0, 1) NaN c-10 NaN (0, 2) r-01 c-00 (1, 0) NaN c-01 (1, 1) NaN c-10 NaN (1, 2) c0 c1 c-00 c-01 c-10 r-00 r-01 r-00 r-01 r-00 r-01r0 (0, 0) (1, 0) (0, 1) (1, 1) (0, 2) (1, 2)

實際上,Pandas允許我們在索引的任何級別上堆疊/取消堆疊。 因此,在前面的示例中,我們也可以堆疊在最外層的索引級別上。 但是,默認(最典型的情況)是在最里面的索引級別進行堆疊/取消堆疊。

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。如有錯誤或未考慮完全的地方,望不吝賜教。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 视觉检测设备_自动化检测设备_CCD视觉检测机_外观缺陷检测-瑞智光电 | 元拓建材集团官方网站 | 美国PARKER齿轮泵,美国PARKER柱塞泵,美国PARKER叶片泵,美国PARKER电磁阀,美国PARKER比例阀-上海维特锐实业发展有限公司二部 | 304不锈钢无缝管_不锈钢管厂家 - 隆达钢业集团有限公司 | 北京中航时代-耐电压击穿试验仪厂家-电压击穿试验机 | 123悬赏网_发布悬赏任务_广告任务平台 | 液氮罐_液氮容器_自增压液氮罐-北京君方科仪科技发展有限公司 | 儋州在线-儋州招聘找工作、找房子、找对象,儋州综合生活信息门户! | 智能终端_RTU_dcm_北斗星空自动化科技 | UV-1800紫外光度计-紫外可见光度计厂家-翱艺仪器(上海)有限公司 | 联系我们-腾龙公司上分客服微信19116098882 | 清水混凝土修复_混凝土色差修复剂_混凝土色差调整剂_清水混凝土色差修复_河南天工 | 十二星座查询(性格特点分析、星座运势解读) - 玄米星座网 | 新疆乌鲁木齐网站建设-乌鲁木齐网站制作设计-新疆远璨网络 | 粤丰硕水性环氧地坪漆-防静电自流平厂家-环保地坪涂料代理 | 润滑油加盟_润滑油厂家_润滑油品牌-深圳市沃丹润滑科技有限公司 琉璃瓦-琉璃瓦厂家-安徽盛阳新型建材科技有限公司 | 选矿设备,选矿生产线,选矿工艺,选矿技术-昆明昆重矿山机械 | 铁艺,仿竹,竹节,护栏,围栏,篱笆,栅栏,栏杆,护栏网,网围栏,厂家 - 河北稳重金属丝网制品有限公司 山东太阳能路灯厂家-庭院灯生产厂家-济南晟启灯饰有限公司 | 全自动不干胶贴标机_套标机-上海今昂贴标机生产厂家 | 流量检测仪-气密性检测装置-密封性试验仪-东莞市奥图自动化科技有限公司 | 宽带办理,电信宽带,移动宽带,联通宽带,电信宽带办理,移动宽带办理,联通宽带办理 | 地磅-电子地磅维修-电子吊秤-汽车衡-无人值守系统-公路治超-鹰牌衡器 | 欧洲MV日韩MV国产_人妻无码一区二区三区免费_少妇被 到高潮喷出白浆av_精品少妇自慰到喷水AV网站 | 酒水灌装机-白酒灌装机-酒精果酒酱油醋灌装设备_青州惠联灌装机械 | 铝扣板-铝方通-铝格栅-铝条扣板-铝单板幕墙-佳得利吊顶天花厂家 elisa试剂盒价格-酶联免疫试剂盒-猪elisa试剂盒-上海恒远生物科技有限公司 | 制氮设备_PSA制氮机_激光切割制氮机_氮气机生产厂家-苏州西斯气体设备有限公司 | 压砖机_电动螺旋压力机_粉末成型压力机_郑州华隆机械tel_0371-60121717 | 激光内雕_led玻璃_发光玻璃_内雕玻璃_导光玻璃-石家庄明晨三维科技有限公司 激光内雕-内雕玻璃-发光玻璃 | 博莱特空压机|博莱特-阿特拉斯独资空压机品牌核心代理商 | 「钾冰晶石」氟铝酸钾_冰晶石_氟铝酸钠「价格用途」-亚铝氟化物厂家 | 蜘蛛车-登高车-高空作业平台-高空作业车-曲臂剪叉式升降机租赁-重庆海克斯公司 | 防堵吹扫装置-防堵风压测量装置-电动操作显示器-兴洲仪器 | 进口便携式天平,外校_十万分之一分析天平,奥豪斯工业台秤,V2000防水秤-重庆珂偌德科技有限公司(www.crdkj.com) | 菲希尔X射线测厚仪-菲希尔库伦法测厚仪-无锡骏展仪器有限责任公司 | 微动开关厂家-东莞市德沃电子科技有限公司 | 伺服电机维修、驱动器维修「安川|三菱|松下」伺服维修公司-深圳华创益 | 耐火浇注料价格-高强高铝-刚玉碳化硅耐磨浇注料厂家【直销】 | 微水泥_硅藻泥_艺术涂料_艺术漆_艺术漆加盟-青岛泥之韵环保壁材 武汉EPS线条_EPS装饰线条_EPS构件_湖北博欧EPS线条厂家 | 称重传感器,测力传感器,拉压力传感器,压力变送器,扭矩传感器,南京凯基特电气有限公司 | 精密五金冲压件_深圳五金冲压厂_钣金加工厂_五金模具加工-诚瑞丰科技股份有限公司 | pos机办理,智能/扫码/二维码/微信支付宝pos机-北京万汇通宝商贸有限公司 |