Pandas系列重塑?

2024-05-12 18:19:28 发布

您现在位置:Python中文网/ 问答频道 /正文

在我看来,它就像熊猫系列中的一只虫子。

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

b有类型序列但无法显示,最后一条语句给出异常,非常长,最后一行是“TypeError:d format:a number is required,not numpy.ndarray”。b、 shape返回(2,2),这与它的类型序列相矛盾。我猜可能是pandas.Series没有实现reforme函数,我正在从np.array调用版本?有人也看到这个错误吗?我在熊猫0.9.1。


Tags: numpyformat类型numberisrequirednot序列
3条回答

可以对序列的数组调用^{}

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

也就是说,我同意这样一个事实,那就是让你试着这样做看起来像个虫子。

您可以直接使用a.reshape((2,2))重塑序列,但不能直接重塑pandas数据帧,因为pandas数据帧没有重塑功能,但您可以在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)

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

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

相关问题 更多 >