Python shape() 方法详解:数组维度、数据结构与应用场景全解析

大家好,本篇文章主要介绍Python的shape()方法及其在编程中的应用变体,并附带详细示例。

那么,让我们开始吧!


使用Python的shape()方法

在对数据及其变体进行分析时,了解数据的规模至关重要。这意味着,在计划对数据进行分析和综合之前,我们需要明确数据的维度。

Python的shape()方法正是在这种情况下发挥作用。

通过shape()方法,可以灵活地获取任何Python对象的维度。它会返回一个元组值,表示Python对象的维度信息。

为了理解输出结果,我们可以通过shape()方法返回的元组来获取对象的维度数量,元组中的每个值代表一个维度的大小。

通常,在更广泛的应用中,shape()方法主要用于获取Pandas和NumPy类型对象在Python中的尺寸。

元组中的每个值都与数组或行/列的实际尺寸相对应。

现在,让我们来看一下接下来的部分中shape()方法的不同变体。


变体一:Pandas的.shape属性

当我们尝试将Pandas类型对象与.shape属性关联以查找其维度时,它会返回一个元组,其中包含行数和列数作为维度值。

语法:

dataframe.shape

通常我们将.shape属性与Pandas数据帧关联,以获取其维度。

示例01:

在这个例子中,我们使用DataFrame()方法从一个Python列表创建了一个数据帧。之后,我们使用dataframe.shape来检查其维度。

由于我们传递的数据有两行两列(2×2),.shape属性会返回行数和列数作为结果。

import pandas as pd 
 
data =[['P','Q'], [0, 1]]
 
data_frame = pd.DataFrame(data)
 
print(data_frame)
print("Shape of the data frame:")
print(data_frame.shape)

输出:

 0  1
0  P  Q
1  0  1
Shape of the data frame:
(2, 2)

示例02:

在这个例子中,我们使用DataFrame()函数创建了一个空的数据帧。然后,通过使用.shape属性,我们可以获取空数据帧的维度。

import pandas as pd 
 
data_frame = pd.DataFrame()
 
print(data_frame)
print("Shape of the data frame:")
print(data_frame.shape)

输出:

Empty DataFrame
Columns: []
Index: []
Shape of the data frame:
(0, 0)

变体二:NumPy的.shape属性

在使用NumPy数据结构时,我们以数组的形式存储数据元素。当我们将.shape属性与NumPy数组关联时,数组的维度会以元组的形式表示。

语法:

array.shape

示例01:

在这里,我们创建了一个没有维度的NumPy数组(即一个标量)。接着,我们对这个数组应用了.shape属性来获取所创建数组的维度。

import numpy as np

ar = np.array(0)

print(ar)
print("Shape of the array:")
print(ar.shape)

输出:

0
Shape of the array:
()

示例02:

在这个例子中,我们创建了一个NumPy数组并向其中添加了元素。这是通过使用numpy.array()函数实现的。现在,我们对数组元素应用.shape属性。

import numpy as np

ar = np.array([[12,20] ,[13,15]])

print(ar)
print("Shape of the array:")
print(ar.shape)

输出:

[[12 20]
 [13 15]]
Shape of the array:
(2, 2)

结论

至此,我们已经结束了关于Python shape()方法的讨论。如果您有任何问题,请随时在下方留言。

关于Kubernetes的更多类似文章,请持续关注我们。

在此之前,祝您学习愉快!:)

bannerAds