【问题标题】:Python - Dimension of Data FramePython - 数据框的维度
【发布时间】:2017-11-06 22:53:01
【问题描述】:

Python 新手。

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

【问题讨论】:

标签: python pandas


【解决方案1】:

df.shape,其中df 是您的数据帧。

【讨论】:

    【解决方案2】:

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

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

    创建示例 DataFrame 和系列

    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 的维数。 DataFrames 总是 2,Series 总是 1:

    df.ndim
    2
    
    s.ndim
    1
    

    棘手的count 方法

    count 方法可用于返回 DataFrame 的每一列/行的非缺失值的数量。这可能非常令人困惑,因为大多数人通常认为 count 只是每行的长度,但事实并非如此。在 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
    

    【讨论】:

      猜你喜欢
      • 2019-03-28
      • 1970-01-01
      • 2016-08-01
      • 2012-04-12
      • 2017-11-12
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多