python将float的二维列表转换为float的二维数组

时间:2014-01-04 03:57:53

标签: python arrays numpy

我正在尝试将一列float读入每个CSV文件的列表中,然后附加到二维列表,稍后将其转换为2D数组,但该数组不会转换为二维浮动的维数组(下面的释义)。我哪里错了?

import numpy
symbols = ['CVX', 'COP', 'MMM', 'BP', 'HMC', 'TM']
AA_lst = []
nSyms = len(symbols)
shortest = 99999
for sym in symbols
    fn = "PricesOf_" + sym + ".csv"
    col = getCSVcolumn( fn, "Close" )
    print( "type(col)="    + str(type(col)) )     # --> <class 'list'>
    print( "type(col[0])=" + str(type(col[0])) )  # --> <class 'float'>
    shortest = min(shortest,len(col))
    AA_lst.append(col)                            # appended as a row of AA_lst

AA = numpy.array( AA_lst )
print( "type=(AA)="     + str(type(AA)) )         # --> <class 'numpy.ndarray'>
print( "type=(AA[0]="   + str(type(AA[0])) )      # --> <class 'list'>
#print( "type=(AA[0,0]=" + str(type(AA[0,0])) )   # --> Error, too many indices

# fix up dimensions (so rows are all the same length)
AA = numpy.resize( AA, (nSyms, shortest) )
print( "type=(AA)="     + str(type(AA)) )         # --> <class 'numpy.ndarray'>
print( "type=(AA[0]="   + str(type(AA[0])) )      # --> <class 'numpy.ndarray'>
print( "type=(AA[0,0]=" + str(type(AA[0,0])) )    # --> <class 'list'>

# desire something of the form:  array([[1,2,3] [4,5,6] [7,8,9]])
# i.e. expecting type(AA[0,0] to be <class 'float'>, not <class 'list'>

2 个答案:

答案 0 :(得分:1)

  1. 确保AA_lst中的列表长度相同。
  2. 考虑使用pandas

答案 1 :(得分:1)

用以下代码替换numpy.resize(...)解决了问题:

AAA_lst = []
for row in AA_lst:
    AAA_lst.append( row[:shortestUnshifted] )

并将AAA_lst提供给numpy.array()