2013-01-17 195 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

請在代碼中添加一些解釋,因爲它有助於理解您的代碼。只有代碼答案是不被接受的。 –