问题 重塑熊猫系列?


它看起来像是熊猫中的一个错误。系列。

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。


9313
2018-01-17 23:48


起源

我对Pandas不是很熟悉,但我知道它的魅力和局限在于为不同维度的数组提供专用对象。所以即使背景中有numpy, pd.Series 永远是1D,和 pd.DataFrame 永远是2D。因此,重塑其中一个对象,就像你做的那样没有多大意义。 - Jaime
和“的方式 你的 做“应该”的方式 你是 做“......羞辱我! - Jaime


答案:


你可以打电话 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。


15
2018-01-18 00:15



我曾经分类过 ndarray 实现固定的维度对象。抓住这个很诱人 reshapes并且不允许它们,但是你在numpy中喜欢的很多很酷的东西都依赖于改变底层数据的维度,例如:摆脱 reshape 和 tile 不再起作用了。可能这是一个小的,不可避免的价格,以重新使用熊猫的numpy引擎。 - Jaime
@Jaime当你尝试这样做时它会导致异常,这肯定是一个错误,要么你应该让它做到DataFrame(和reindex),要么该方法不可用? - Andy Hayden
关键是你不能在不破坏其他功能的情况下使它不可用,除非你愿意重做很多numpy给你的免费。我同意这不好,但它可能真的是最好的。 - Jaime
@isulsz我不使用熊猫,所以我真的不在乎,我不反对改变行为 Series,提交错误报告。但问题是无法访问 reshape 从你的对象内部,但知道是否调用 reshape你的对象来自用户,应该得到一个 NotImplemented 例外,或来自另一个依赖的numpy方法 reshape 做它的事。在numpy, matrix 应该是一个2D对象,但你可以将它重塑为1D或3D,因为如果没有,你将无法,例如, np.tile 一个 matrix。 - Jaime
downvote的任何理由? - Andy Hayden


reshape函数将新形状作为元组而不是多个参数:

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]])

1
2018-02-09 20:23





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

  1. 将DataFrame转换为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
2018-03-05 17:21





只需使用以下代码:

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

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


0
2017-11-15 12:47



请添加一些解释和代码,因为它有助于理解您的代码。代码只有答案是不受欢迎的。 - Bhargav Rao♦