存储这些向量,但是在Python中使用哪种数据结构

2024-09-27 02:15:12 发布

您现在位置:Python中文网/ 问答频道 /正文

以下循环的每次迭代都生成一个维数为50x1的向量 我喜欢将循环中的所有向量集中存储在一个数据结构中。在

  def get_y_hat(y_bar, x_train, theta_Ridge_Matrix):
     print theta_Ridge_Matrix.shape
     print theta_Ridge_Matrix.shape[0]
     for i in range(theta_Ridge_Matrix.shape[0]):
        yH = np.dot(x_train, theta_Ridge_Matrix[i].T)
        print yH

我应该使用哪种数据结构?我是Python新手,但基于我在线研究的内容,有两个选项:numpy数组和列表列表

我需要在这个方法之外访问50个元素的每个向量。我会存储200到500个向量。在

有人能给我这种数据结构的示例代码吗

谢谢


Tags: 数据结构列表gethatdefbartrain向量
2条回答

我认为将循环中的数据存储在dict中,然后将其转换为^{}(它是在numpy数组之上构建的)应该是一个有效的解决方案,允许您进一步将数据作为一个整体或单个向量进行处理。在

例如:

import pandas as pd
import numpy as np

data = {}
# this would be your loop
for i in range(50):
    data['run_%02d' % i] = np.random.randn(50)
data = pd.DataFrame(data) # sorted keys of the dict will be the columns 

可以将单个向量作为属性访问,也可以通过以下键访问:

^{pr2}$

或者进一步分析整个数据:

print data.mean()

run_00   -0.015224
run_01   -0.006971
..
run_48   -0.115935
run_49    0.147738

或者使用matplotlib查看您的数据

我建议使用numpy来安装它

在此站点的windows上:

http://sourceforge.net/projects/numpy/files/NumPy/

一些你如何使用它的例子。在

import numpy as np

我们将创建一个数组,命名为mat

^{pr2}$

数组使用动词“T”进行转置

>>> mat.T
array([[ 1.02063865, -0.82198131],
       [ 1.52885147, 0.20995583],
       [ 0.45588211, 0.31997462]])

任何数组的形状都可以通过使用\verb“整形”方法进行更改

>>> mat = np.random.randn(3,6)
array([[ 2.01139326, 1.33267072, 1.2947112 , 0.07492725, 0.49765694,
         0.01757505],
       [ 0.42309629, 0.95921276, 0.55840131, -1.22253606, -0.91811118,
         0.59646987],
       [ 0.19714104, -1.59446001, 1.43990671, -0.98266887, -0.42292461,
        -1.2378431 ]])
>>> mat.reshape(2,9)
array([[ 2.01139326, 1.33267072, 1.2947112 , 0.07492725, 0.49765694,
         0.01757505, 0.42309629, 0.95921276, 0.55840131],
       [-1.22253606, -0.91811118, 0.59646987, 0.19714104, -1.59446001,
         1.43990671, -0.98266887, -0.42292461, -1.2378431 ]])

我们可以使用\动词“shape”属性更改变量的形状。在

>>> mat = np.random.randn(4,3)
>>> mat.shape
(4, 3)
>>> mat
array([[-1.47446507, -0.46316836, 0.44047531],
       [-0.21275495, -1.16089705, -1.14349478],
       [-0.83299338, 0.20336677, 0.13460515],
       [-1.73323076, -0.66500491, 1.13514327]])
>>> mat.shape = 2,6
>>> mat.shape
(2, 6)

>>> mat
array([[-1.47446507, -0.46316836, 0.44047531, -0.21275495, -1.16089705,
        -1.14349478],
       [-0.83299338, 0.20336677, 0.13460515, -1.73323076, -0.66500491,
         1.13514327]])

相关问题 更多 >

    热门问题