【问题标题】:Convert Python numeric list to numpy array of float将 Python 数字列表转换为浮点数的 numpy 数组
【发布时间】:2018-09-25 14:13:57
【问题描述】:

我有一个数字列表,需要转换为 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)

【问题讨论】:

  • 你试过了吗?你可以打印出来看看。
  • 你可以写arr = np.array(list)arr = np.array([1.5, 2.5, 3.5])
  • arr = np.array(lst) 怎么样?请不要在类后命名变量。
  • 您是否将np.array/np.ndarray 上的一维索引与二维索引混淆了?
  • @smci np.array 函数返回一个 ndarray,因此您的评论读起来相当混乱。

标签: python arrays numpy indexing


【解决方案1】:

GaussMatrixdtype 设置为np.float64 怎么样?

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

【讨论】:

  • 谢谢,但我收到以下错误:AttributeError: 'list' object has no attribute 'astype'
  • 我更新了我的答案。我希望您的 GaussMatrix 是一个 numpy 数组。这也适用于嵌套的 python 列表。它保持原始对象的形状,因此不需要重新整形。
【解决方案2】:

首先请不要使用'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')

【讨论】:

  • 你可以使用 my_array.reshape(n,m)
猜你喜欢
  • 1970-01-01
  • 2019-10-31
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-20
  • 2011-07-18
  • 1970-01-01
相关资源
最近更新 更多