iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python3快速入门(十三)——Pan
  • 814
分享到

Python3快速入门(十三)——Pan

入门快速Pan 2023-01-31 08:01:17 814人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

一、pandas数据结构简介 Pandas有三种主要数据结构,Series、DataFrame、Panel。Series是带有标签的一维数组,可以保存任何数据类型(整数,字符串,浮点数,python对象等),轴标签统称为索引(index)

一、pandas数据结构简介

Pandas有三种主要数据结构,Series、DataFrame、Panel。
Series是带有标签的一维数组,可以保存任何数据类型(整数,字符串,浮点数,python对象等),轴标签统称为索引(index)。
DataFrame是带有标签的二维数据结构,具有index(行标签)和columns(列标签)。如果传递index或columns,则会用于生成的DataFrame的index或columns。
Panel是一个三维数据结构,由items、major_axis、minor_axis定义。items(条目),即轴0,每个条目对应一个DataFrame;major_axis(主轴),即轴1,是每个DataFrame的index(行);minor_axis(副轴),即轴2,是每个DataFrame的columns(列)。

二、Series

1、Series简介

Series是能够保存任何类型数据(整数,字符串,浮点数,Python对象等)的一维标记数组,轴标签统称为index(索引)。
series是一种一维数据结构,每一个元素都带有一个索引,其中索引可以为数字或字符串。Series结构名称:
Python3快速入门(十三)——Pandas数据结构

2、Series对象构造

Series构造函数如下:
pandas.Series( data, index, dtype, copy)
data:构建Series的数据,可以是ndarray,list,dict,constants。
index:索引值必须是唯一的和散列的,与数据的长度相同。 如果没有索引被传递,默认为np.arange(n)。
dtype:数据类型,如果没有,将推断数据类型。
copy:是否复制数据,默认为false。
(1)创建一个空的 Series

import pandas as pd

if __name__ == "__main__":
    s = pd.Series()
    print(s)

# output:
# Series([], dtype: float64)

(2)使用ndarray创建Series
使用ndarray作为数据时,传递的索引必须与ndarray具有相同的长度。 如果没有传递索引值,那么默认的索引是range(n),其中n是数组长度,即[0,1,2,3…. range(len(array))-1] - 1]。

import pandas as pd
import numpy as np

if __name__ == "__main__":
    data = np.array(['a', 1, 2, 4, 6])
    s = pd.Series(data,index=[101, 102, 103, 'hello', 'world'])
    print(s)

# output:
# 101      a
# 102      1
# 103      2
# hello    4
# world    6
# dtype: object

不传递任何索引时,默认分配从0到len(data)-1的索引。

import pandas as pd
import numpy as np

if __name__ == "__main__":
    data = np.array(['a', 1, 2, 4, 6])
    s = pd.Series(data)
    print(s)

# output:
# 0    a
# 1    1
# 2    2
# 3    4
# 4    6
# dtype: object

(3)使用字典创建Series
使用字典(dict)作为数据时,如果没有指定索引,则按排序顺序取得字典键以构造索引。 如果传递索引,索引中与标签对应的数据中的值将被取出。

import pandas as pd

if __name__ == "__main__":
    data = {'a': 1, 2: 'hello', 'b': 'hello world'}
    s = pd.Series(data)
    print(s)

# output:
# a              1
# 2          hello
# b    hello world
# dtype: object

传递索引时,索引顺序保持不变,缺少的元素使用NaN(不是数字)填充。

import pandas as pd

if __name__ == "__main__":
    data = {'a': 1, 2: 'hello', 'b': 'hello world', "hello": "world"}
    s = pd.Series(data, index=['a', 'b', "hello", 'd'])
    print(s)

# output:
# a                  1
# b        hello world
# hello          world
# d                NaN
# dtype: object

(4)使用标量创建Series
使用标量值作为数据,则必须提供索引,会重复标量值以匹配索引的长度。

import pandas as pd

if __name__ == "__main__":
    s = pd.Series(100, index=[1, 2, 3])
    print(s)

# output:
# 1    100
# 2    100
# 3    100
# dtype: int64

(5)使用list、tuple创建Series
使用list、tuple作为数据时,传递的索引必须与list、tuple具有相同的长度。 如果没有传递索引值,那么默认的索引是range(n),其中n是list的长度,即[0,1,2,3…. range(len(list))-1] - 1]。

import pandas as pd

if __name__ == "__main__":
    s = pd.Series([1, 2, 3, "hello"])
    print(s)

# output:
# 0        1
# 1        2
# 2        3
# 3    hello
# dtype: object

3、Series数据的访问

Series中的数据可以使用有序序列的方式进行访问。

import pandas as pd

if __name__ == "__main__":
    s = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])
    print(s[0])
    print(s[-1])
    print(s[-3:])

# output:
# 1
# 5
# c    3
# d    4
# e    5
# dtype: int64

Series像一个固定大小的字典,可以通过索引标签获取和设置值,使用索引标签值检索单个元素,使用索引标签值列表检索多个元素。如果使用不包含在索引内的标签,则会出现异常。

import pandas as pd

if __name__ == "__main__":
    s = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])
    s['a'] = 101
    print(s['a'])
    print(s[0])
    print(s[['a', 'b', 'e']])

# output:
# 101
# 101
# a    101
# b      2
# e      5
# dtype: int64

4、Series属性

Series对象的属性和方法如下:
Series.axes:返回行轴标签列表
Series.dtype:返回对象的数据类型
Series.empty:如果对象为空,返回True
Series.ndim:返回底层数据的维数,默认为1
Series.size:返回基础数据中的元素数
Series.values:将对象作为ndarray返回
Series.head():返回前n行
Series.tail():返回后n行

import pandas as pd

if __name__ == "__main__":
    s = pd.Series(["Bauer", 30, 90], index=['Name', 'Age', 'Score'])
    print("Series=================")
    print(s)
    print("axes===================")
    print(s.axes)
    print("dtype==================")
    print(s.dtype)
    print("empty==================")
    print(s.empty)
    print("ndim===================")
    print(s.ndim)
    print("size===================")
    print(s.size)
    print("values=================")
    print(s.values)
    print("head()=================")
    print(s.head(2))
    print("tail()=================")
    print(s.tail(2))

# output:
# Series=================
# Name     Bauer
# Age         30
# Score       90
# dtype: object
# axes===================
# [Index(['Name', 'Age', 'Score'], dtype='object')]
# dtype==================
# object
# empty==================
# False
# ndim===================
# 1
# size===================
# 3
# values=================
# ['Bauer' 30 90]
# head()=================
# Name    Bauer
# Age        30
# dtype: object
# tail()=================
# Age      30
# Score    90
# dtype: object

三、DataFrame

1、DataFrame简介

数据帧(DataFrame)是二维的表格型数据结构,即数据以行和列的表格方式排列,DataFrame是Series的容器
DataFrame的结构名称如下:
Python3快速入门(十三)——Pandas数据结构

2、DataFrame的特点

数据帧(DataFrame)的功能特点如下:
(1)底层数据列是不同的类型
(2)大小可变
(3)标记轴(行和列)
(4)可以对行和列执行算术运算

3、DataFrame对象构造

pandas.DataFrame( data, index, columns, dtype, copy)
data:构建DataFrame的数据,可以是ndarray,series,map,lists,dict,constant和其它DataFrame。
index:行索引标签,如果没有传递索引值,索引默认为np.arrange(n)。
columns:列索引标签,如果没有传递索列引值,默认列索引是np.arange(n)。
dtype:每列的数据类型。
copy:如果默认值为False,则此命令(或任何它)用于复制数据。
(1)创建空的DataFrame

import pandas as pd

if __name__ == "__main__":
    df = pd.DataFrame()
    print(df)

# output:
# Empty DataFrame
# Columns: []
# Index: []

(2)使用list创建DataFrame
使用单个列表或嵌套列表作为数据创建DataFrame时,如果不指定index或columns,默认使用range(len(list))作为index,对于单列表,默认columns=[0],对于嵌套列表,默认columns为内层列表的长度的range。

import pandas as pd

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]
    df = pd.DataFrame(data)
    print(df)
    df = pd.DataFrame(data, index=['a', 'b', 'c', 'h', 'e'], columns=['A'])
    print(df)

# output:
#    0
# 0  1
# 1  2
# 2  3
# 3  4
# 4  5
#    A
# a  1
# b  2
# c  3
# h  4
# e  5

指定index或columns时,index的长度必须与list长度匹配,columns的长度必须与list的内层列表长度匹配,否则将报错。

import pandas as pd

if __name__ == "__main__":
    data = [['Alex', 25], ['Bob', 26], ['Bauer', 24]]
    df = pd.DataFrame(data, columns=['Name', 'Age'])
    print(df)
    df = pd.DataFrame(data, columns=['Name', 'Age'], dtype=float)
    print(df)

# output:
#     Name  Age
# 0   Alex   25
# 1    Bob   26
# 2  Bauer   24
#     Name   Age
# 0   Alex  25.0
# 1    Bob  26.0
# 2  Bauer  24.0

(3)使用ndarray和list的字典创建DataFrame
使用ndarray、list组成的字典作为数据创建DataFrame时,所有的ndarray、list必须具有相同的长度。如果传递index,则index的长度必须等于ndarray、list的长度,columns为字典的key组成的集合。如果没有传递index,则默认情况下,index将为range(n),其中n为list或ndarray长度。

import pandas as pd

if __name__ == "__main__":
    data = {'Name': ['Tom', 'Jack', 'Steve', 'Ricky'], 'Age': [28, 34, 29, 42]}
    df = pd.DataFrame(data)
    print(df)
    df = pd.DataFrame(data, index=['rank1', 'rank2', 'rank3', 'rank4'])
    print(df)

# output:
#     Name  Age
# 0    Tom   28
# 1   Jack   34
# 2  Steve   29
# 3  Ricky   42
#         Name  Age
# rank1    Tom   28
# rank2   Jack   34
# rank3  Steve   29
# rank4  Ricky   42

(4)使用字典列表创建DataFrame
使用字典列表作为数据创建DataFrame时,默认使用range(len(list))作为index,字典键的集合作为columns,如果字典没有相应键值对,其值使用NaN填充。当指定columns时,如果columns使用字典键集合以外元素作为columns的元素,则使用NaN进行填充,并提取出columns指定的数据源字典中相应的键值对。

import pandas as pd

if __name__ == "__main__":
    data = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}]
    df = pd.DataFrame(data)
    print(df)
    df = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b', 'c', 'A', 'B'])
    print(df)

# output:
#    a   b     c
# 0  1   2   NaN
# 1  5  10  20.0
#         a   b     c   A   B
# first   1   2   NaN NaN NaN
# second  5  10  20.0 NaN NaN

(5)使用Series字典创建DataFrame
使用Series字典作为数据创建DataFrame时,得到的DataFrame的index是所有Series的index的并集,字典键的集合作为columns。

import pandas as pd

if __name__ == "__main__":
    data = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
            'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
    df = pd.DataFrame(data, columns=['one', 'two'])
    print(df)
    df = pd.DataFrame(data, columns=['one', 'two', 'three'])
    print(df)
    df = pd.DataFrame(data, index=['a', 'b', 'c', 'A'], columns=['one', 'two', 'three'])
    print(df)

# output:
#    one  two
# a  1.0    1
# b  2.0    2
# c  3.0    3
# d  NaN    4
#    one  two three
# a  1.0    1   NaN
# b  2.0    2   NaN
# c  3.0    3   NaN
# d  NaN    4   NaN
#    one  two three
# a  1.0  1.0   NaN
# b  2.0  2.0   NaN
# c  3.0  3.0   NaN
# A  NaN  NaN   NaN

4、DataFrame列操作

通过字典键可以进行列选择,获取DataFrame中的一列数据。

import pandas as pd

if __name__ == "__main__":
    data = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
            'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
    df = pd.DataFrame(data, columns=['one', 'two'])
    print(df)
    print(df['one'])

# output:
#    one  two
# a  1.0    1
# b  2.0    2
# c  3.0    3
# d  NaN    4
# a    1.0
# b    2.0
# c    3.0
# d    NaN
# Name: one, dtype: float64

通过向DataFrame增加相应的键和Series值,可以为DataFrame增加一列。

import pandas as pd

if __name__ == "__main__":
    data = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
            'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
    df = pd.DataFrame(data, columns=['one', 'two'])
    print(df)
    df['three'] = pd.Series([10, 20, 30], index=['a', 'b', 'c'])
    print(df)
    df['four'] = df['one'] + df['three']
    print(df)

# output:
#    one  two
# a  1.0    1
# b  2.0    2
# c  3.0    3
# d  NaN    4
#    one  two  three
# a  1.0    1   10.0
# b  2.0    2   20.0
# c  3.0    3   30.0
# d  NaN    4    NaN
#    one  two  three  four
# a  1.0    1   10.0  11.0
# b  2.0    2   20.0  22.0
# c  3.0    3   30.0  33.0
# d  NaN    4    NaN   NaN

通过del可以删除DataFrame的列。

import pandas as pd

if __name__ == "__main__":
    data = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
            'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']),
            'three': pd.Series([10, 20, 30], index=['a', 'b', 'c'])}
    df = pd.DataFrame(data, columns=['one', 'two', 'three'])
    print(df)
    del(df['two'])
    print(df)

# output:
#  one  two  three
# a  1.0    1   10.0
# b  2.0    2   20.0
# c  3.0    3   30.0
# d  NaN    4    NaN
#    one  three
# a  1.0   10.0
# b  2.0   20.0
# c  3.0   30.0
# d  NaN    NaN

5、DataFrame行选择

DataFrame行选择可以通过将行标签传递给loc函数来选择行,也可以通过将整数位置传递给iloc()函数来选择行,返回Series,Series的名称是检索的标签,Series的index为DataFrame的columns。

import pandas as pd

if __name__ == "__main__":
    data = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
            'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']),
            'three': pd.Series([10, 20, 30], index=['a', 'b', 'c'])}
    df = pd.DataFrame(data, columns=['one', 'two', 'three'])
    print(df.loc['a'])
    print(df.iloc[0])

# output:
# one       1.0
# two       1.0
# three    10.0
# Name: a, dtype: float64
# one       1.0
# two       1.0
# three    10.0
# Name: a, dtype: float64

DataFrame多行选择可以通过使用:运算符对DataFrame进行行切片操作,选择多行。

import pandas as pd

if __name__ == "__main__":
    data = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
            'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']),
            'three': pd.Series([10, 20, 30], index=['a', 'b', 'c'])}
    df = pd.DataFrame(data, columns=['one', 'two', 'three'])
    print(df)
    print(df[2:4])

# output:
#    one  two  three
# a  1.0    1   10.0
# b  2.0    2   20.0
# c  3.0    3   30.0
# d  NaN    4    NaN
#    one  two  three
# c  3.0    3   30.0
# d  NaN    4    NaN

DataFrame的行追加通过append函数实现。

import pandas as pd

if __name__ == "__main__":
    df = pd.DataFrame([["Bauer", 20], ["Jack", 30]], index=["rank1", "rank2"], columns=['Name', 'Age'])
    df2 = pd.DataFrame([["Alex", 18], ["Bob", 28]], index=["rank3", "rank3"], columns=['Name', 'Age'])
    df = df.append(df2)
    print(df)

# output:
#         Name  Age
# rank1  Bauer   20
# rank2   Jack   30
# rank3   Alex   18
# rank3    Bob   28

DataFrame的行删除通过将索引标签传递给drop函数进行行删除, 如果标签重复,则会删除多行。

import pandas as pd

if __name__ == "__main__":
    df = pd.DataFrame([["Bauer", 20], ["Jack", 30]], index=["rank1", "rank2"], columns=['Name', 'Age'])
    df2 = pd.DataFrame([["Alex", 18], ["Bob", 28]], index=["rank3", "rank3"], columns=['Name', 'Age'])
    df = df.append(df2)
    print(df)
    df = df.drop("rank2")
    print(df)

# output:
#         Name  Age
# rank1  Bauer   20
# rank2   Jack   30
# rank3   Alex   18
# rank3    Bob   28
#         Name  Age
# rank1  Bauer   20
# rank3   Alex   18
# rank3    Bob   28

6、DataFrame属性

DataFrame对象的属性和方法如下:
DataFrame.T:转置行和列
DataFrame.axes:返回一个列,行轴标签和列轴标签作为唯一的成员。
DataFrame.dtypes:返回对象的数据类型
DataFrame.empty:如果NDFrame完全为空,返回True
DataFrame.ndim:返回轴/数组维度的大小
DataFrame.shape:返回表示DataFrame维度的元组
DataFrame.size:返回DataFrame的元素数
DataFrame.values:将对象作为ndarray返回
DataFrame.head():返回前n行
DataFrame.tail():返回后n行

import pandas as pd

if __name__ == "__main__":
    df = pd.DataFrame([["Bauer", 30, 90], ['Jack', 32, 98], ['Bob', 28, 78]], columns=['Name', 'Age', 'Score'])
    print("DataFrame=================")
    print(df)
    print("T======================")
    print(df.T)
    print("axes===================")
    print(df.axes)
    print("dtypes==================")
    print(df.dtypes)
    print("empty==================")
    print(df.empty)
    print("ndim===================")
    print(df.ndim)
    print("shape==================")
    print(df.shape)
    print("size===================")
    print(df.size)
    print("values=================")
    print(df.values)
    print("head()=================")
    print(df.head(2))
    print("tail()=================")
    print(df.tail(2))

# output:
# DataFrame=================
#     Name  Age  Score
# 0  Bauer   30     90
# 1   Jack   32     98
# 2    Bob   28     78
# T======================
#            0     1    2
# Name   Bauer  Jack  Bob
# Age       30    32   28
# Score     90    98   78
# axes===================
# [RangeIndex(start=0, stop=3, step=1), Index(['Name', 'Age', 'Score'], dtype='object')]
# dtypes==================
# Name     object
# Age       int64
# Score     int64
# dtype: object
# empty==================
# False
# ndim===================
# 2
# shape==================
# (3, 3)
# size===================
# 9
# values=================
# [['Bauer' 30 90]
#  ['Jack' 32 98]
#  ['Bob' 28 78]]
# head()=================
#     Name  Age  Score
# 0  Bauer   30     90
# 1   Jack   32     98
# tail()=================
#    Name  Age  Score
# 1  Jack   32     98
# 2   Bob   28     78

四、Panel

1、Panel简介

Panel 是三维的数据结构,是DataFrame的容器,Panel的3个轴如下:
items - axis 0,每个项目对应于内部包含的数据帧(DataFrame)。
major_axis - axis 1,是每个数据帧(DataFrame)的索引(行)。
minor_axis - axis 2,是每个数据帧(DataFrame)的列。

2、Panel对象构建

pandas.Panel(data, items, major_axis, minor_axis, dtype, copy)
data:构建Panel的数据,采取各种形式,如:ndarray,series,map,lists,dict,constant和另一个数据帧(DataFrame)。
items:axis=0
major_axis:axis=1
minor_axis:axis=2
dtype:每列的数据类型
copy:复制数据,默认 - false
(1)创建空Panel

import pandas as pd

if __name__ == "__main__":
    p = pd.Panel()
    print(p)

# output:
# class 'pandas.core.panel.Panel'>
# Dimensions: 0 (items) x 0 (major_axis) x 0 (minor_axis)
# Items axis: None
# Major_axis axis: None
# Minor_axis axis: None

(2)使用3D ndarray创建Panel

import pandas as pd
import numpy as np

if __name__ == "__main__":
    data = np.random.rand(2, 4, 5)
    p = pd.Panel(data, items=["item1", "item2"], major_axis=[1, 2, 3, 4], minor_axis=['a', 'b', 'c', 'd', 'e'])
    print(p)
    print("item1")
    print(p["item1"])
    print(p.major_xs(2))
    print(p.minor_xs('b'))

# output:
# <class 'pandas.core.panel.Panel'>
# Dimensions: 2 (items) x 4 (major_axis) x 5 (minor_axis)
# Items axis: item1 to item2
# Major_axis axis: 1 to 4
# Minor_axis axis: a to e
# item1
#           a         b         c         d         e
# 1  0.185626  0.976123  0.566263  0.273208  0.675442
# 2  0.209664  0.205190  0.217200  0.158447  0.400683
# 3  0.499591  0.963321  0.759330  0.089930  0.362824
# 4  0.723158  0.585642  0.629246  0.886086  0.493039
#       item1     item2
# a  0.209664  0.592154
# b  0.205190  0.661562
# c  0.217200  0.743716
# d  0.158447  0.055882
# e  0.400683  0.245760
#       item1     item2
# 1  0.976123  0.630320
# 2  0.205190  0.661562
# 3  0.963321  0.741791
# 4  0.585642  0.729366

(3)使用DataFrame字典创建Panel

import pandas as pd
import numpy as np

if __name__ == "__main__":
    data = {'Table1': pd.DataFrame(np.random.randn(4, 3),
                                   index=['rank1', 'rank2', 'rank3', 'rank4'],
                                   columns=['Name', 'Age', 'Score']),
            'Table2': pd.DataFrame(np.random.randn(4, 3),
                                   index=['rank1', 'rank2', 'rank3', 'rank4'],
                                   columns=['Name', 'Age', 'Score']
                                   )
            }
    p = pd.Panel(data)
    print(p)

# output:
# <class 'pandas.core.panel.Panel'>
# Dimensions: 2 (items) x 4 (major_axis) x 3 (minor_axis)
# Items axis: Table1 to Table2
# Major_axis axis: rank1 to rank4
# Minor_axis axis: Name to Score

3、Panel数据索引

使用Items访问Panel可以获取相应的DataFrame。

import pandas as pd
import numpy as np

if __name__ == "__main__":
    data = {'Table1': pd.DataFrame(np.random.randn(4, 3),
                                   index=['rank1', 'rank2', 'rank3', 'rank4'],
                                   columns=['Name', 'Age', 'Score']),
            'Table2': pd.DataFrame(np.random.randn(4, 3),
                                   index=['rank1', 'rank2', 'rank3', 'rank4'],
                                   columns=['Name', 'Age', 'Score']
                                   )
            }
    p = pd.Panel(data)
    print(p['Table1'])

# output:
#            Name       Age     Score
# rank1 -1.240644 -0.820041  1.656150
# rank2  1.830655 -0.258068 -0.728560
# rank3  1.268695  1.259693 -1.005151
# rank4 -0.139876  0.611589  2.343394

使用panel.major_axis(key)函数访问Panel数据,需要传递Major_axis的值作为key,返回DataFrame,DataFrame的index为Minor_axis,columns为Items。

import pandas as pd
import numpy as np

if __name__ == "__main__":
    data = {'Table1': pd.DataFrame(np.random.randn(4, 3),
                                   index=['rank1', 'rank2', 'rank3', 'rank4'],
                                   columns=['Name', 'Age', 'Score']),
            'Table2': pd.DataFrame(np.random.randn(4, 3),
                                   index=['rank1', 'rank2', 'rank3', 'rank4'],
                                   columns=['Name', 'Age', 'Score']
                                   )
            }
    p = pd.Panel(data)
    print(p.major_xs('rank2'))

# output:
#          Table1    Table2
# Name   1.664996  0.326820
# Age    0.952639  0.686095
# Score -0.473985 -0.343404

使用panel.minor_axis(key)函数访问Panel数据,需要传递Minor_axis的值作为key,返回DataFrame,DataFrame的index为Major_axis,columns为Items。

import pandas as pd
import numpy as np

if __name__ == "__main__":
    data = {'Table1': pd.DataFrame(np.random.randn(4, 3),
                                   index=['rank1', 'rank2', 'rank3', 'rank4'],
                                   columns=['Name', 'Age', 'Score']),
            'Table2': pd.DataFrame(np.random.randn(4, 3),
                                   index=['rank1', 'rank2', 'rank3', 'rank4'],
                                   columns=['Name', 'Age', 'Score']
                                   )
            }
    p = pd.Panel(data)
    print(p.minor_xs('Name'))

# output:
#          Table1    Table2
# rank1 -1.314702 -0.198485
# rank2  0.055324  0.295646
# rank3 -0.352192 -0.523549
# rank4 -4.002903 -0.577389

4、Panel属性

Panel对象的属性和方法如下:
Panel.T:转置行和列
Panel.axes:返回一个列,行轴标签和列轴标签作为唯一的成员。
Panel.dtypes:返回对象的数据类型
Panel.empty:如果NDFrame完全为空,返回True
Panel.ndim:返回轴/数组维度的大小
Panel.shape:返回表示DataFrame维度的元组
Panel.size:返回DataFrame的元素数
Panel.values:将对象作为ndarray返回

import pandas as pd
import numpy as np

if __name__ == "__main__":
    array1 = np.random.randn(4, 3)
    array2 = np.random.randn(4, 3)
    data = {'Table1': pd.DataFrame(array1,
                                   index=['rank1', 'rank2', 'rank3', 'rank4'],
                                   columns=['Name', 'Age', 'Score']),
            'Table2': pd.DataFrame(array2,
                                   index=['rank1', 'rank2', 'rank3', 'rank4'],
                                   columns=['Name', 'Age', 'Score']
                                   )
            }
    p = pd.Panel(data)
    print("panel=================")
    print(p)
    print("axes===================")
    print(p.axes)
    print("dtypes==================")
    print(p.dtypes)
    print("empty==================")
    print(p.empty)
    print("ndim===================")
    print(p.ndim)
    print("shape==================")
    print(p.shape)
    print("size===================")
    print(p.size)
    print("values=================")
    print(p.values)
    print(p["Table1"])
    print(array1)

# output:
# panel=================
# <class 'pandas.core.panel.Panel'>
# Dimensions: 2 (items) x 4 (major_axis) x 3 (minor_axis)
# Items axis: Table1 to Table2
# Major_axis axis: rank1 to rank4
# Minor_axis axis: Name to Score
# axes===================
# [Index(['Table1', 'Table2'], dtype='object'), Index(['rank1', 'rank2', 'rank3', 'rank4'], dtype='object'), Index(['Name', 'Age', 'Score'], dtype='object')]
# dtypes==================
# Table1    float64
# Table2    float64
# dtype: object
# empty==================
# False
# ndim===================
# 3
# shape==================
# (2, 4, 3)
# size===================
# 24
# values=================
# [[[ 0.22914664 -0.88176603  0.48050365]
#   [-0.15099586  0.23380446  0.20165317]
#   [-0.13652604  1.08191771  0.60361811]
#   [-0.81742392 -0.09018878  1.62892609]]
# 
#  [[-0.72965894  0.58207009  0.15309812]
#   [ 0.06467707  1.13494668 -0.19074456]
#   [-0.53869056  1.28244925 -0.01832724]
#   [-0.26831567  0.65912009  0.38607594]]]
#            Name       Age     Score
# rank1  0.229147 -0.881766  0.480504
# rank2 -0.150996  0.233804  0.201653
# rank3 -0.136526  1.081918  0.603618
# rank4 -0.817424 -0.090189  1.628926
# [[ 0.22914664 -0.88176603  0.48050365]
#  [-0.15099586  0.23380446  0.20165317]
#  [-0.13652604  1.08191771  0.60361811]
#  [-0.81742392 -0.09018878  1.62892609]]

--结束END--

本文标题: Python3快速入门(十三)——Pan

本文链接: https://www.lsjlt.com/news/192915.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python3快速入门(十三)——Pan
    一、Pandas数据结构简介 Pandas有三种主要数据结构,Series、DataFrame、Panel。Series是带有标签的一维数组,可以保存任何数据类型(整数,字符串,浮点数,Python对象等),轴标签统称为索引(index)...
    99+
    2023-01-31
    入门 快速 Pan
  • Python3快速入门(十五)——Pan
    一、函数应用 1、函数应用简介 如果要将自定义函数或其它库函数应用于Pandas对象,有三种使用方式。pipe()将函数用于表格,apply()将函数用于行或列,applymap()将函数用于元素。 2、表格函数应用 可以通过将函数对象和...
    99+
    2023-01-31
    入门 快速 十五
  • Python3快速入门(十四)——Pan
    一、DataFrame IO 1、CSV文件 pandas.read_csv(filepath_or_buffer, na_values='NAN', parse_dates=['Last Update'])从CSV文件中读取数...
    99+
    2023-01-31
    入门 快速 十四
  • Python3快速入门(十)——Pyth
    一、socket模块简介 Python 提供了两个级别访问的网络服务,低级别的网络服务支持基本的 Socket,提供了标准的BSD Sockets API,可以访问底层操作系统Socket接口的全部方法;高级别的网络服务模块 Socket...
    99+
    2023-01-31
    入门 快速 Pyth
  • Python3快速入门(十二)——Num
    一、NumPy简介 1、NumPy简介 NumPy(Numerical Python) 是 Python 语言的一个扩展程序库,支持大量的维度数组与矩阵运算,同时对数组运算提供了大量的数学函数库。Numpy 是一个运行速度非常快的数学库,...
    99+
    2023-01-31
    入门 快速 十二
  • Python3快速入门(十六)——Mat
    一、Matplotlib简介 1、Matplotlib简介 Matplotlib是 Python 2D-绘图领域使用最广泛的套件,可以简易地将数据图形化,并且提供多样化的输出格式。matplotlib有两个接口,一个是状态机层的接口,通过...
    99+
    2023-01-31
    入门 快速 十六
  • Python3快速入门(十一)——Pyt
    一、mysql-connector 驱动 1、mysql-connector 简介 mysql-connector 是 MySQL 官方提供的驱动器。使用pipenv进行包管理,安装命令如下:pipenv install mysql-co...
    99+
    2023-01-31
    入门 快速 Pyt
  • Python3快速入门(十八)——PyI
    一、PyInstaller简介 1、PyInstaller简介 PyInstaller是一个跨平台的Python应用打包工具,支持 Windows/Linux/MacOS三大主流平台,能够把 Python 脚本及其所在的 Python 解...
    99+
    2023-01-31
    入门 快速 PyI
  • Python3快速入门(三)——Pyth
    一、Python3标准数据类型 Python3 中有六种标准数据类型:A、Number(数字)B、String(字符串)C、List(列表)D、Tuple(元组)E、Set(集合)F、Dictionary(字典)Python3 的六种标准...
    99+
    2023-01-31
    入门 快速 Pyth
  • Python3快速入门
    Python3快速入门Python3快速入门(一)——Python简介https://blog.51cto.com/9291927/2385592Python3快速入门(二)——Python3基础https://blog.51cto.com...
    99+
    2023-01-31
    入门 快速
  • python3.x 快速入门
    Edit the > 2018/6/15 11:26:53 1认识Python 人生苦短,我用python - 优雅,明确,简单 是python设计哲学 - python的设计目标之一, 是让代码具备高度的可阅读性 ...
    99+
    2023-01-31
    入门 快速
  • Python3快速入门(一)——Pyth
    一、Python简介 1、Python简介 Python是一种解释型、面向对象、动态数据类型的高级程序设计语言,由荷兰Guido van Rossum于1989年底发明,第一个公开发行版于1991年发布,Python源代码遵循 GPL(G...
    99+
    2023-01-31
    入门 快速 Pyth
  • Python3快速入门(九)——Pyth
    一、Python线程模块 1、线程简介 一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆栈组成。线程是进程中的一个实体,是被系统独立调度和分派的基本单位,线程本身不拥有系统资源,与进程内的其它线程共享进程的所有资源。一个进程...
    99+
    2023-01-31
    入门 快速 Pyth
  • Python3快速入门——(3)dict
    #先回忆下列表的操作animals=["cat","dog","rabbit"] #找到list中的某个值(第一种方法)for animal in animals: if(animal=="cat"): ...
    99+
    2023-01-31
    入门 快速 dict
  • Python3快速入门(四)——Pyth
    一、Python包简介 1、包 Python中使用包管理模块,包通常对应一个目录,必须在目录下创建一个init.py模块,init.py模块的模块名称即为包名,Python才会将目录解析为包。init.py文件内可以定义初始化包的内容,导...
    99+
    2023-01-31
    入门 快速 Pyth
  • Python3快速入门(八)——Pyth
    1、JSON简介 JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,是基于ECMAScript的一个子集。 2、json模块简介 Python3 中可以使用 json 模块来对 JSON 数据...
    99+
    2023-01-31
    入门 快速 Pyth
  • Python3快速入门(二)——Pyth
    一、Python3语法基础 1、Python3编码 默认情况下,Python 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串,可以为Python源码文件指定不同的编码,如下:# -*- coding: utf-8 -...
    99+
    2023-01-31
    入门 快速 Pyth
  • Python3快速入门(七)——Pyth
    1、re模块简介 re 模块提供 Perl 风格的正则表达式模式,使 Python 语言拥有全部的正则表达式功能。 2、正则表达式模式 模式字符串使用特殊的语法来表示一个正则表达式:正则表达式模式中的字母和数字匹配同样的字符串;多数字母和...
    99+
    2023-01-31
    入门 快速 Pyth
  • Python3快速入门(五)——Pyth
    一、函数定义 1、函数定义 Python 定义函数使用 def 关键字,一般格式如下: def function_name(parameter_list): pass 默认情况下,参数值和参数名称按函数声明中定义的顺序进行匹配。函...
    99+
    2023-01-31
    入门 快速 Pyth
  • Python3快速入门(六)——Pyth
    一、面向对象技术简介 1、面向对象简介 面向对象编程(Object Oriented Programing,OOP)是一种编程思想,OOP把对象当成程序的一个基本单元,一个对象包含数据和操作数据的方法。面向对象编程的三大特性如下:A、封装...
    99+
    2023-01-31
    入门 快速 Pyth
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作