Python shape() 方法 - 你需要知道的一切!

您好,读者! 本文讲述了 Python shape() 方法及其变体在编程中的例子。

让我们开始吧!!!


使用 Python shape() 方法

当涉及到数据和其变体的分析时,意识到数据的数量非常重要,也就是说,在我们计划分析数据并对其进行合成之前,我们需要了解数据的尺寸。

这是当Python shape()方法进入图像时。

使用 shape() 方法,可以灵活地获取任何 Python 对象的尺寸. 是的,它会返回指示 Python 对象的尺寸的 tuple 值。

要了解输出,form() 方法返回的 tuple 是代表对象尺寸值的元素的实际数目。

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

tuple 表示的每一个值都与数组或行/列的实际维度相匹配。

现在让我们在下一节中看看相同的变体。


变量 1: Pandas 形状属性

当我们尝试将 Pandas类型对象与寻找维度的形状方法关联时,它会返回代表行和列为维度值的tuple。

合成:**

1dataframe.shape

我们通常将形状作为属性与Panda数据框架相关联,以获得相同的尺寸。

第01章:

在本示例中,我们使用 DataFrame() 方法创建了从 Python 列表的数据框架,然后我们将 dataframe.shape 应用到检查尺寸。

由于我们传递的数据有两个行和两个列(2x2),形状方法会返回结果的行和列数量。

1import pandas as pd 
2
3data =[['P','Q'], [0, 1]]
4
5data_frame = pd.DataFrame(data)
6
7print(data_frame)
8print("Shape of the data frame:")
9print(data_frame.shape)

出发点:**

10 1
20 P Q
31 0 1
4Shape of the data frame:
5(2, 2)

第02章:

在本示例中,我们使用 DataFrame() 函数创建了一个空数据框,然后,使用 shape() 方法,我们可以获得空数据框的尺寸。

1import pandas as pd 
2
3data_frame = pd.DataFrame()
4
5print(data_frame)
6print("Shape of the data frame:")
7print(data_frame.shape)

出发点:**

1Empty DataFrame
2Columns: []
3Index: []
4Shape of the data frame:
5(0, 0)

变量 2: NumPy 形状方法

使用 NumPy 数据结构,我们以数组的形式存储数据元素. 当我们将 shape() 方法与 NumPy 数组相关联时,数组的尺寸以 tuple 的形式表示。

合成:**

1array.shape

第01章:

在这里,我们创建了一个没有尺寸的NumPy数组,然后我们将 shape()方法应用到数组中,以获取所创建的数组的尺寸。

1import numpy as np
2
3ar = np.array(0)
4
5print(ar)
6print("Shape of the array:")
7print(ar.shape)

出发点:**

10
2Shape of the array:
3()

第02章:

在本示例中,我们创建了 NumPy 数组并添加了元素,这是通过 numpy.array() 函数实现的,现在我们将 shape() 方法应用到元素数组中。

1import numpy as np
2
3ar = np.array([[12,20] ,[13,15]])
4
5print(ar)
6print("Shape of the array:")
7print(ar.shape)

出发点:**

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

结论

由此,我们已经到这个话题的尽头. 请自由评论下面,如果你遇到任何问题。

有关Kubernetes的更多此类帖子,与我们保持一致。

直到那时,快乐的学习! :)

Published At
Categories with 技术
comments powered by Disqus