最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python pandas軸旋轉(zhuǎn)stack和unstack的使用說明

 更新時(shí)間:2021年03月05日 14:58:39   作者:Asher117  
這篇文章主要介紹了Python pandas軸旋轉(zhuǎn)stack和unstack的使用說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

摘要

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

首先,要知道以下五點(diǎn):

1.stack:將數(shù)據(jù)的列“旋轉(zhuǎn)”為行

2.unstack:將數(shù)據(jù)的行“旋轉(zhuǎn)”為列

3.stack和unstack默認(rèn)操作為最內(nèi)層

4.stack和unstack默認(rèn)旋轉(zhuǎn)軸的級(jí)別將會(huì)成果結(jié)果中的最低級(jí)別(最內(nèi)層)

5.stack和unstack為一組逆運(yùn)算操作

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

1、創(chuàng)建DataFrame,行索引名為state,列索引名為number

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

2、將DataFrame的列旋轉(zhuǎn)為行,即stack操作

result = data.stack()
result

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

3、將DataFrame的行旋轉(zhuǎn)為列,即unstack操作

result.unstack()

從下面結(jié)果理解上述點(diǎn)3,unstack操作默認(rèn)將內(nèi)層索引number旋轉(zhuǎn)為列索引。

同時(shí),也可以指定分層級(jí)別或者索引名稱來指定操作級(jí)別,下面做錯(cuò)同樣會(huì)得到上面的結(jié)果。

4、stack和unstack逆運(yùn)算

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

data2.unstack().stack()

補(bǔ)充:使用Pivot、Pivot_Table、Stack和Unstack等方法在Pandas中對(duì)數(shù)據(jù)變形(重塑)

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

一、Pivot

pivot函數(shù)用于從給定的表中創(chuàng)建出新的派生表,pivot有三個(gè)參數(shù):索引、列和值。具體如下:

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

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

假設(shè)我們有以下數(shù)據(jù):

我們將數(shù)據(jù)讀取進(jìn)來:

from collections import OrderedDict
from pandas import DataFrame
import pandas as pd
import 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)

得到結(jié)果為:

  item color user bm
0 Item1  red  1 1
1 Item1  blue  2 2
2 Item2  red  3 3
3 Item2 black  4 4

接下來,我們對(duì)以上數(shù)據(jù)進(jìn)行變形:

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

得到的結(jié)果為:

color black blue red
item         
Item1 None   2  1
Item2   4 None  3

注意:可以使用以下方法對(duì)原始數(shù)據(jù)和轉(zhuǎn)換后的數(shù)據(jù)進(jìn)行等效查詢:

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

結(jié)果為:

['1']
['1']

在以上的示例中,轉(zhuǎn)化后的數(shù)據(jù)不包含bm的信息,它僅包含我們在pivot方法中指定列的信息。下面我們對(duì)上面的例子進(jìn)行擴(kuò)展,使其在包含user信息的同時(shí)也包含bm信息。

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

結(jié)果為:

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

從結(jié)果中我們可以看出:Pandas為新表創(chuàng)建了分層列索引。我們可以用這些分層列索引來過濾出單個(gè)列的值,例如:使用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')

得到的結(jié)果為:

ValueError: Index contains duplicate entries, cannot reshape

因此,在調(diào)用pivot函數(shù)之前,我們必須確保我們指定的列和行沒有重復(fù)的數(shù)據(jù)。如果我們無法確保這一點(diǎn),我們可以使用pivot_table這個(gè)方法。

pivot_table方法實(shí)現(xiàn)了類似pivot方法的功能,它可以在指定的列和行有重復(fù)的情況下使用,我們可以使用均值、中值或其他的聚合函數(shù)來計(jì)算重復(fù)條目中的單個(gè)值。

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

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.
    接下來我們來看一個(gè)示例:
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)

結(jié)果為:

color black blue  red
item          
Item1 None   2   1
Item2   4 None None

實(shí)際上,pivot_table()是pivot()的泛化,它允許在數(shù)據(jù)集中聚合具有相同目標(biāo)的多個(gè)值。

三、Stack/Unstack

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

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

得到的結(jié)果為:

         c0   c1
r0 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-01
r0 (0, 0) (1, 0) (0, 1) (1, 1) (0, 2) (1, 2)

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

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。

相關(guān)文章

  • pytorch通過訓(xùn)練結(jié)果的復(fù)現(xiàn)設(shè)置隨機(jī)種子

    pytorch通過訓(xùn)練結(jié)果的復(fù)現(xiàn)設(shè)置隨機(jī)種子

    這篇文章主要介紹了pytorch通過訓(xùn)練結(jié)果的復(fù)現(xiàn)設(shè)置隨機(jī)種子的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • Python torch.flatten()函數(shù)案例詳解

    Python torch.flatten()函數(shù)案例詳解

    這篇文章主要介紹了Python torch.flatten()函數(shù)案例詳解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • 利用python-pypcap抓取帶VLAN標(biāo)簽的數(shù)據(jù)包方法

    利用python-pypcap抓取帶VLAN標(biāo)簽的數(shù)據(jù)包方法

    今天小編就為大家分享一篇利用python-pypcap抓取帶VLAN標(biāo)簽的數(shù)據(jù)包方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • 正則表達(dá)式在Python中的應(yīng)用小結(jié)

    正則表達(dá)式在Python中的應(yīng)用小結(jié)

    正則表達(dá)式是一種強(qiáng)大的文本模式匹配工具,它可以幫助我們快速地檢索、替換或提取字符串中的特定模式,在本文中,我將通過一些示例代碼,詳細(xì)介紹正則表達(dá)式在Python中的應(yīng)用,感興趣的朋友一起看看吧
    2024-07-07
  • 簡單的Python人臉識(shí)別系統(tǒng)

    簡單的Python人臉識(shí)別系統(tǒng)

    這篇文章主要介紹了Python人臉識(shí)別系統(tǒng)的實(shí)現(xiàn),文中講解非常詳細(xì),代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • 詳解Python自建logging模塊

    詳解Python自建logging模塊

    本篇文章給大家詳細(xì)分析了Python自建logging模塊的方法和代碼分享,有需要的朋友參考學(xué)習(xí)下吧。
    2018-01-01
  • Python中np.where()的使用方式

    Python中np.where()的使用方式

    這篇文章主要介紹了Python中np.where()的使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • 解決Pycharm 運(yùn)行后沒有輸出的問題

    解決Pycharm 運(yùn)行后沒有輸出的問題

    這篇文章主要介紹了解決Pycharm 運(yùn)行后沒有輸出的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • Python字典查找數(shù)據(jù)的5個(gè)基礎(chǔ)操作方法

    Python字典查找數(shù)據(jù)的5個(gè)基礎(chǔ)操作方法

    Python字典是另一種可變?nèi)萜髂P?且可存儲(chǔ)任意類型對(duì)象,如字符串、數(shù)字、元組等其他容器模型,下面這篇文章主要給大家介紹了關(guān)于Python字典查找數(shù)據(jù)的5個(gè)基礎(chǔ)操作方法,需要的朋友可以參考下
    2022-06-06
  • Python生成短uuid的方法實(shí)例詳解

    Python生成短uuid的方法實(shí)例詳解

    python的uuid都是32位的,比較長,處理起來效率比較低。這篇文章主要介紹了Python生成短uuid的方法,需要的朋友可以參考下
    2018-05-05

最新評(píng)論

台南市| 宣化县| 泸西县| 丰宁| 曲阳县| 江华| 泸西县| 武胜县| 安岳县| 郸城县| 万宁市| 安化县| 曲水县| 盐边县| 车险| 治县。| 光泽县| 白玉县| 彩票| 达尔| 丰城市| 吉安县| 成安县| 阜平县| 大庆市| 凌源市| 江西省| 嵊州市| 大安市| 江城| 乳山市| 广安市| 鄂温| 徐水县| 延安市| 邛崃市| 无为县| 容城县| 山阳县| 大竹县| 太和县|