2017-08-08 8 views
0

私はアイテムのリストを持っています。行と列が項目である行列(または三角行列)を作成したいとし、行列の値がf(x, y)で、fが関数で、x, yがインデックスです。パンダ - リストから行列を作成するにはどうすればよいですか?

並列計算(つまりmap())をサポートする実装を使用することができれば理想的です。

最もクリーンな方法は何ですか?

+0

あなたが例を与えることができますか? –

答えて

1

私は、これはあなたが望むかもしれないと思う:

import pandas as pd 
import numpy as np 

listofitems = ['apple', 'pear', 'banana', 'grape'] 

df = pd.DataFrame(np.matrix(np.random.rand(4,4)), columns=listofitems, index=listofitems) 

enter image description here

、あなたのf(x,y)を取得するには:

df['banana']['pear'] 
>> 0.34471005596459292 

あなたはそれがnp.triuまたはnp.tril例えば

た三角形得ることができます

df = pd.DataFrame(np.tril(np.matrix(np.random.rand(4,4))), columns=listofitems, index=listofitems) enter image description here

0

あなたはリストからグリッドを作成するnumpy.meshgrid()を使用して、各セルの機能を評価することができます。

a = np.array([1,2,3,4]) 
xx, yy = np.meshgrid(a,a) 
z = xx + yy 
# out: array([[2, 3, 4, 5], 
#    [3, 4, 5, 6], 
#    [4, 5, 6, 7], 
#    [5, 6, 7, 8]]) 

あなたはまた、より複雑な関数を作成することができます

def f(xx, yy): 
    return np.sin(yy) + np.cos(xx) 
z = f(xx, yy) 
# out: array([[ 1.38177329, 0.42532415, -0.14852151, 0.18782736], 
#    [ 1.44959973, 0.49315059, -0.08069507, 0.25565381], 
#    [ 0.68142231, -0.27502683, -0.84887249, -0.51252361], 
#    [-0.21650019, -1.17294933, -1.74679499, -1.41044612]]) 
関連する問題