2016-06-29 13 views
1

のは、私は非常に単純なデータフレームを持っているとしましょう:私は、ランダムな長さのnumpyの配列を生成する関数を定義して追加しようと思って今とValueError

import pandas as pd 
df = pd.DataFrame(np.full((6), 1)) 

私は2-D arrayを取得するためにdfに関数を適用しようとすると

import numpy as np 
def func(row): 
    l = np.full((np.random.random_integer(5)), 1) 
    return np.hstack(l, row) 

:末尾に値を与え

df.apply(func, axis=1), 

私は、このようなエラーを得た:

ValueError: Shape of passed values is (6, 2), indices imply (6, 1) 

あなたは問題が何であるかを知っていますし、それを修正する方法?前もって感謝します!まず、そのタプルを渡すあなたが、np.random.random_integersたい第二hstackがタプルを取る

+0

'random_integet'はnp関数ではありません – EdChum

+0

@EdChumを実行してコードを更新できますか?私はすでに間違いを訂正しています。おかげで – user5779223

答えて

1

は、第三に、あなたはそれが、この場合にはそうで揃えることができる何かを返す必要がSeries:私はトンを得る

In [213]: 
df = pd.DataFrame(np.full((6), 1)) 
def func(row): 
    l = np.full((np.random.random_integers(5)), 1) 
    return pd.Series(np.hstack((l, row))) 

In [214]:  
df.apply(func, axis=1) 

Out[214]: 
    0 1 2 3 4 5 
0 1.0 1.0 1.0 NaN NaN NaN 
1 1.0 1.0 NaN NaN NaN NaN 
2 1.0 1.0 NaN NaN NaN NaN 
3 1.0 1.0 1.0 NaN NaN NaN 
4 1.0 1.0 1.0 1.0 1.0 NaN 
5 1.0 1.0 1.0 1.0 1.0 1.0 

注意

C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\numpy\core\numeric.py:301: FutureWarning: in the future, full(3, 1) will return an array of dtype('int32') 
    format(shape, fill_value, array(fill_value).dtype), FutureWarning) 
C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\numpy\core\numeric.py:301: FutureWarning: in the future, full(2, 1) will return an array of dtype('int32') 
    format(shape, fill_value, array(fill_value).dtype), FutureWarning) 
C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\numpy\core\numeric.py:301: FutureWarning: in the future, full(1, 1) will return an array of dtype('int32') 
    format(shape, fill_value, array(fill_value).dtype), FutureWarning) 
C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\numpy\core\numeric.py:301: FutureWarning: in the future, full(4, 1) will return an array of dtype('int32') 
    format(shape, fill_value, array(fill_value).dtype), FutureWarning) 
C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\numpy\core\numeric.py:301: FutureWarning: in the future, full(5, 1) will return an array of dtype('int32') 
    format(shape, fill_value, array(fill_value).dtype), FutureWarning) 

DFコール属性valuesからNPの配列を取得するには:

上記に関する警告の
df.apply(func, axis=1).values 
+0

あなたの魔法の答えをありがとう!しかし、numpyの2次元配列や行列に転送することはできますか?ありがとう! – user5779223

+0

希望の出力で質問を編集することによって何を意味するのか説明できます – EdChum

+0

私は既に質問を編集しました。実際には、出力は系列の代わりに数値列の配列にしたいだけです。ありがとう。 – user5779223