Python - 数据框的维度

问题描述 投票:0回答:2

Python 新手。

在 R 中,您可以使用 dim(...) 获取矩阵的维数。 Python Pandas 中数据框对应的函数是什么?

python pandas
2个回答
184
投票

df.shape
,其中
df
是您的 DataFrame。

示例

df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]})

print(df)

   col1  col2
0     1     4
1     2     5
2     3     6
df.shape
(3, 2) # i.e., 3 rows, 2 columns

43
投票

获取 DataFrame 或 Series 维度信息的所有方法总结

有多种方法可以获取有关 DataFrame 或 Series 属性的信息。

创建示例数据框和系列

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape
属性

shape
属性返回 DataFrame 中行数和列数的两项元组。对于一个系列,它返回一个单项元组。

df.shape
(3, 2)

s.shape
(3,)

len
功能

要获取 DataFrame 的行数或获取 Series 的长度,请使用

len
函数。将返回一个整数。

len(df)
3

len(s)
3

size
属性

要获取 DataFrame 或 Series 中的元素总数,请使用

size
属性。对于 DataFrame,这是行数和列数的乘积。对于系列,这相当于
len
函数:

df.size
6

s.size
3

ndim
属性

ndim
属性返回 DataFrame 或 Series 的维度数。 DataFrame 始终为 2,Series 始终为 1:

df.ndim
2

s.ndim
1

棘手的
count
方法

count
方法可用于返回DataFrame每列/行的非缺失值的数量。这可能会非常令人困惑,因为大多数人通常认为计数只是每行的长度,但事实并非如此。当在 DataFrame 上调用时,会返回一个 Series,其中包含索引中的列名称和非缺失值的数量作为值。

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

对于一个系列,只有一个轴用于计算,因此它只返回一个标量:

s.count()
2

使用
info
方法检索元数据

info
方法返回每列的非缺失值数量和数据类型

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes
© www.soinside.com 2019 - 2024. All rights reserved.