繁体   English   中英

将 Python 数字列表转换为 numpy 浮点数组

[英]Convert Python numeric list to numpy array of float

我有一个需要转换为 45 x 45 数组中的浮点数的数字列表。

gauss_matrix = [list of 2025 float numbers]
mat_template = np.zeros([45, 45])
for rows in np.arange(45):
    for columns in np.arange(45):
          mat_template[rows, columns] = float(gauss_matrix[np.arange(2025)])

这是否从第 0 行开始,循环遍历第 0-44 列。 然后从第 2 行开始,循环遍历第 0-44 列等等?

已解决代码:(感谢您的帮助!)

   with open('gaussfilter.csv', 'r+') as gauss:  # Let's me read and write gaussfilter.csv

GaussFilterData = gauss.readlines()  # Reads the lines of the csv file
# print("GaussFilterData: \n", GaussFilterData)

GaussList = []  # Empty list which will be used to append values to from the csv file
# print("GaussList 1: \n", GaussMatrix)

for lines in GaussFilterData:  # Loops through each row of data in gaussfilter.csv
    # print("lines: \n", lines)
    for row in np.arange(45):  # Looping through each row and splitting up the list by commas, while converting each value to a float and not a string
        GaussList.append(float(lines.split(',')[row]))  # Appending each row to GaussList

# print("\nGaussList 2: \n", GaussList)

# Making the array of values from GaussList
gauss = np.zeros([45, 45])  # Matrix of zeros, the zeros are placeholders for the values in GaussList
# print("gauss: \n", gauss)

Counter = -1  # Counter has to start at -1 so that it begins at 0 when referring to row 0 and column 0
for rows in np.arange(45):  # Loop through rows 0 - 44
        for columns in np.arange(45):  # As we are looping through row 0, loop through all 45 columns
            Counter = Counter + 1  # Counter keeps track of the number of cells in the matrix (2025)
            gauss[rows][columns] = GaussList[Counter]

     print("gauss array: \n", gauss)

怎么样设置dtype你的GaussMatrixnp.float64

GaussMatrix = np.array(GaussMatrix, dtype=np.float)

首先请不要使用'list'。因此,我将其更改为my_list。

您可以使用 'np.array()' 创建一个数组,并且您可以使用可选的 'dtype' 标志指定您的数据类型。

>>> import numpy as np
>>> my_list = [1.5, 2.5, 3.5]
>>> my_array = np.array(my_list,dtype=" ")

并且您始终可以使用以下方法检查您的数据类型:

>>> my_array.dtype
dtype('float64')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM