重塑熊猫系列?

时间:2013-01-17 23:48:25

标签: python numpy pandas reshape

它看起来像是pandas.Series中的一个错误。

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

b有类型Series但不能显示,最后一个语句给出异常,非常冗长,最后一行是“TypeError:%d format:需要一个数字,而不是numpy.ndarray”。 b.shape返回(2,2),这与其类型系列相矛盾。我猜也许pandas.Series没有实现重塑功能,我从np.array调用版本?任何人都看到这个错误?我在大熊猫0.9.1。

5 个答案:

答案 0 :(得分:19)

您可以在系列的数组中调用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

说,我同意这个事实,你试图这样做就像一个bug。

答案 1 :(得分: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.

Reshape实际上是在Series中实现的,并将返回一个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]])

答案 2 :(得分:0)

你可以直接使用a.reshape((2,2))来重塑一个系列,但你不能直接重塑一个pandas DataFrame,因为pandas DataFrame没有重塑功能,但是你可以对numpy ndarray进行重塑:

  1. 将DataFrame转换为numpy ndarray
  2. 做重塑
  3. 转换回来
  4. e.g。

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

答案 3 :(得分:0)

只需使用以下代码:

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

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

答案 4 :(得分:0)

例如,我们有一个系列。我们可以像这样将其更改为数据框;

a = pd.DataFrame(a)