我想使用一个单独的函数来计算矩阵值,并将第一列和第一行作为输入。你知道吗
我希望收到关于优化以下代码的建议:
#imports
import numpy as np
import pandas as pd
#numpy variant
#creation of sample matrix
x_range = range(-180, -80, 20)
y_range = range(5, 30, 5)
ma = np.zeros(shape=(6,6))
ma[0,1:] = x_range
ma[1:,0] = y_range
ma[0,0] = np.nan
# test function:
def test_func(x, y):
z = (x + y) / 10
return z
#looping
for y in range(1, len(ma[0,:])):
for x in range(1, len(ma[:,0])):
#print ma[0, x], ma[y, 0]
ma[x, y] = test_func(ma[0, x], ma[y, 0])
ma
array([[ nan, -180. , -160. , -140. , -120. , -100. ],
[ 5. , -17.5, -17. , -16.5, -16. , -15.5],
[ 10. , -15.5, -15. , -14.5, -14. , -13.5],
[ 15. , -13.5, -13. , -12.5, -12. , -11.5],
[ 20. , -11.5, -11. , -10.5, -10. , -9.5],
[ 25. , -9.5, -9. , -8.5, -8. , -7.5]])
#pandas variant
cols = x_range
idx = y_range
#dataframe
df = pd.DataFrame(np.zeros(shape=(5,5)), index=idx, columns=cols)
df.index.name = 'Y-Range'
df.columns.name = 'X-Range'
df
X-Range -180 -160 -140 -120 -100
Y-Range
5 0 0 0 0 0
10 0 0 0 0 0
15 0 0 0 0 0
20 0 0 0 0 0
25 0 0 0 0 0
#looping
for col in range(0, (len(df.columns))):
for ind in range(0, (len(df.index))):
df.iloc[ind, col] = test_func(df.index[ind], df.columns[col])
df
X-Range -180 -160 -140 -120 -100
Y-Range
5 -18 -16 -14 -12 -10
10 -17 -15 -13 -11 -9
15 -17 -15 -13 -11 -9
20 -16 -14 -12 -10 -8
25 -16 -14 -12 -10 -8
#rounding due to console settings
这正是我想要的。你知道吗
但有没有更好的方法,更有效,避免循环?你知道吗
注: 谢谢你的回复。你知道吗
在设置} 发挥作用。作为一个矢量化的方法,这一定很快。因此,循环替换将如下所示-
ma
之后,可以通过扩展其中一个切片部分的维度来替换向量化方法的嵌套循环:ma[0,1:]
和add与另一个切片ma[1:,0]
,这将使^{请注意,编写
ma[0,1:][:,None]
的更简洁的方法是ma[0,1:,None]
。你知道吗可以使用^{} 和^{} :
相关问题 更多 >
编程相关推荐