2013-01-17 44 views
7

它在我看来就像是熊猫系列中的一个错误。重塑熊猫系列?

a = pd.Series([1,2,3,4]) 
b = a.reshape(2,2) 
b 

B有型系列,但无法显示,最后一条语句给人例外,很长时间,最后一行是“类型错误:%d格式:需要一个数字,不numpy.ndarray”。 b.shape返回(2,2),这与它的类型系列相矛盾。我猜可能熊猫。系列没有实现重塑功能,我打电话给np.array的版本?任何人都看到这个错误?我在熊猫0.9.1。

+2

我对熊猫不是很熟悉,但是我明白它的魅力和限制在于为不同维度的数组提供专用对象。所以即使背景中有numpy,“pd.Series”总是1D,“pd.DataFrame”总是2D。因此,重新塑造其中一个对象的方式并不合理。 – Jaime

+0

“你**做事的方式”应该是“你做**的方式”......对我感到羞耻! – Jaime

回答

11

可以呼吁reshape阵列系列之一:(?你忽略指数)

In [4]: a.values.reshape(2,2) 
Out[4]: 
array([[1, 2], 
     [3, 4]], dtype=int64) 

其实,我认为它不会总是有意义申请reshape一个系列,和你在想它正确只是numpy的的重塑:

a.reshape?
Docstring: See numpy.ndarray.reshape

这么说,我同意的事实,它让你尝试这样做看起来像一个错误的。

+0

我曾将子类“ndarray”实现为一个固定的维度对象。它很容易抓住“重塑”并且不允许它们,但是你在numpy中喜欢的很多很酷的东西都依赖于改变底层数据的尺寸,例如,摆脱'reshape'和'瓦''不再工作。可能这是一个小的,不可避免的,重复使用Pandas中的numpy引擎的代价。 – Jaime

+0

@Jaime事实上,当你尝试这样做的时候它会导致一个异常,肯定是一个bug,要么让它做到DataFrame(和reindex),要么该方法不可用? –

+0

关键是,除非您愿意重做大量numpy免费提供的功能,否则无法在不破坏其他功能的情况下使其不可用。我同意这不是很好,但它可能确实是最好的。 – Jaime

1

的重塑功能采用新形状为一个元组,而不是为多个参数:

In [4]: a.reshape? 
Type:  function 
String Form:<function reshape at 0x1023d2578> 
File:  /Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/numpy/core/fromnumeric.py 
Definition: numpy.reshape(a, newshape, order='C') 
Docstring: 
Gives a new shape to an array without changing its data. 

Parameters 
---------- 
a : array_like 
    Array to be reshaped. 
newshape : int or tuple of ints 
    The new shape should be compatible with the original shape. If 
    an integer, then the result will be a 1-D array of that length. 
    One shape dimension can be -1. In this case, the value is inferred 
    from the length of the array and remaining dimensions. 

重塑在系列实际执行,并会返回一个ndarray:

In [11]: a 
Out[11]: 
0 1 
1 2 
2 3 
3 4 

In [12]: a.reshape((2, 2)) 
Out[12]: 
array([[1, 2], 
     [3, 4]]) 
0

可以直接使用a.reshape((2,2))来重塑一个Series,但是你不能直接重塑一个熊猫DataFrame,因为没有熊猫DataFrame的重塑功能,但是你可以在numpy ndarray上重塑形状:

  1. 转换数据帧到numpy的ndarray
  2. 做重塑
  3. 转换回

例如

a = pd.DataFrame([[1,2,3],[4,5,6]]) 
b = a.as_matrix().reshape(3,2) 
a = pd.DataFrame(b) 
0

只要使用此代码如下:

b=a.values.reshape(2,2) 

我认为这将帮助你。 你可以直接使用reshape()函数,但它会给出未来的警告

+1

请在代码中添加一些解释,因为它有助于理解您的代码。只有代码答案是不被接受的。 –