我有一個項目列表。我想製作一個矩陣(或三角矩陣),其中行和列是項目,矩陣值是f(x, y)
,其中f
是一個函數,而x, y
是索引。熊貓 - 如何從列表中製作矩陣?
如果可以使用支持並行計算的實現(即map()),那是理想的。
什麼是最乾淨的方式?
我有一個項目列表。我想製作一個矩陣(或三角矩陣),其中行和列是項目,矩陣值是f(x, y)
,其中f
是一個函數,而x, y
是索引。熊貓 - 如何從列表中製作矩陣?
如果可以使用支持並行計算的實現(即map()),那是理想的。
什麼是最乾淨的方式?
我認爲這可能是你想要什麼:
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)
然後讓你的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)
可以使用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]])
你能舉個例子嗎? –