代码之家  ›  专栏  ›  技术社区  ›  SebMa

为什么选择我的熊猫数据帧的形状是错误的?

  •  4
  • SebMa  · 技术社区  · 8 年前

    我有一个熊猫数据框叫 df 哪里 df.shape (53, 80) 其中索引和列都是 int .

    如果我像这样选择第一行,我得到:

    df.loc[0].shape
    (80,)
    

    而不是:

    (1,80)
    

    但是那时 df.loc[0:0].shape df[0:1].shape 两者都显示了正确的形状。

    2 回复  |  直到 8 年前
        1
  •  3
  •   jpp    8 年前

    df.loc[0] 返回 pd.Series 对象,表示通过索引提取的单行数据。

    df.loc[0:0] 返回 pd.DataFrame 对象,表示通过切片提取的数据帧中的一行数据。

    如果打印这些操作的结果,您可以更清楚地看到这一点:

    import pandas as pd, numpy as np
    
    df = pd.DataFrame(np.arange(9).reshape(3, 3))
    
    res1 = df.loc[0]
    res2 = df.loc[0:0]
    
    print(type(res1), res1, sep='\n')
    
    <class 'pandas.core.series.Series'>
    0    0
    1    1
    2    2
    Name: 0, dtype: int32
    
    print(type(res2), res2, sep='\n')
    
    <class 'pandas.core.frame.DataFrame'>
       0  1  2
    0  0  1  2
    

    该惯例遵循numpy索引/切片。这是自然的,因为熊猫是建立在麻木的阵列上。

    arr = np.arange(9).reshape(3, 3)
    
    print(arr[0].shape)    # (3,), i.e. 1-dimensional
    print(arr[0:0].shape)  # (0, 3), i.e. 2-dimensional
    
        2
  •  2
  •   niraj    8 年前

    当你打电话的时候 df.iloc[0] ,选择第一行,类型为 Series 鉴于,在其他情况下 df.iloc[0:0] 它正在切片行,属于类型 dataframe .和 系列 根据 pandas Series documentation 以下内容:

    带有轴标签的一维数据阵列

    鉴于 数据帧 二维 ( pandas Dataframe documentation )。

    尝试运行以下行以查看区别:

    print(type(df.iloc[0]))
    # <class 'pandas.core.series.Series'>
    
    print(type(df.iloc[0:0]))
    # <class 'pandas.core.frame.DataFrame'>