【发布时间】:2016-01-20 07:07:40
【问题描述】:
我想使用单独的函数计算矩阵值,并将第一列和第一行作为输入。
我希望收到有关优化以下代码的建议:
#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[1,2] / 10 = -15.5编辑后ma[1,2] = -17。对吗?
标签: python arrays numpy pandas vectorization