【问题标题】:Shape command does not return the column number when the data frame has only column当数据框只有列时,shape命令不返回列号
【发布时间】:2021-10-16 14:03:14
【问题描述】:

数据集如下所述 定义变量是考试。 考试.shape = (29,2)

    |Hours| |Pass| 
0   |0.5 |    |0|  
1   |0.75|    |0|  
2   |1.00|    |0|  
3   |1.25|    |0|  
4   |1.50|    |0| 

截图中附有清晰的图片

X = exam.Hours  
y = exam.Pass 

X.shape = (29,)  # The column number one is not mentioned   
y.shape = (29,) # The column value is not mentioned 

预期结果

X.shape = (29,1)    
y.shape = (29,1)

【问题讨论】:

  • 一列系列,wjich 是一维对象,因此是单个形状值。 Shape 是一个元组,因此显示为 (29,)。

标签: python pandas dataframe numpy dataset


【解决方案1】:
In [200]: df
Out[200]: 
   age  rank  height  weight
0   20     2     155      53
1   15     7     159      60
2   34     6     180      75
3   40     5     163      80
4   60     1     170      49
In [201]: df.shape
Out[201]: (5, 4)

以下是一个Series,只有长度,没有列:

In [202]: df['height']
Out[202]: 
0    155
1    159
2    180
3    163
4    170
Name: height, dtype: int64
In [203]: df['height'].shape
Out[203]: (5,)

带有列表的索引返回带有列号的数据框。注意显示的区别:

In [204]: df[['height']]
Out[204]: 
   height
0     155
1     159
2     180
3     163
4     170
In [205]: df[['height']].shape
Out[205]: (5, 1)

【讨论】:

    【解决方案2】:

    两个数组都是一维的,您希望添加一个额外的维度。你需要在你的数组上解压一个新的轴。

    >>> x = np.random.rand(29)
    
    >>> x.shape
    (29,)
    

    使用索引:

    >>> x = x[..., np.newaxis] # i.e. x[..., None]
    
    >>> x.shape
    (29, 1)
    

    或使用np.expand_dims 实用程序:

    >>> x = np.expand_dims(x, -1)
    
    >>> x.shape
    (29, 1)
    

    【讨论】:

    猜你喜欢
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多