导出循环的numpy直方图输出到列表,而无需数组信息和格式

时间:2018-10-31 14:11:31

标签: python-3.x numpy scipy histogram tolist

我正在遍历由多个列表编译的数据循环。我最终将要创建一个直方图,但是我希望将直方图函数的装箱输出导出到列表中。目前,数据已导出一个列表,该列表看起来像一个数组-我认为这是来自numpy的原始输出,但是我似乎无法解决问题。理想情况下,我想要的是每个子列表的合并值,而不包含有关数组和合并标头的信息-任何指针?

bins = [0, 1.06, 5.01, 10.01, 15]
sigmafreqdist=[]

for i in alldata:
    freqdist = np.histogram(i,bins)
    sigmafreqdist.append(freqdist)


#print the list 
print(sigmafreqdist)

我得到的结果是这样的:

(array([ 6, 14,  2,  0], dtype=int64),
  array([ 0.  ,  1.06,  5.01, 10.01, 15.  ])),
 (array([ 5, 14,  0,  0], dtype=int64),
  array([ 0.  ,  1.06,  5.01, 10.01, 15.  ])),
 (array([31, 19,  2,  0], dtype=int64),
  array([ 0.  ,  1.06,  5.01, 10.01, 15.  ])),
 (array([12, 43,  1,  0], dtype=int64),
  array([ 0.  ,  1.06,  5.01, 10.01, 15.  ])),
 (array([30, 34,  1,  0], dtype=int64),
  array([ 0.  ,  1.06,  5.01, 10.01, 15.  ])),
 (array([12, 13,  0,  0], dtype=int64),
  array([ 0.  ,  1.06,  5.01, 10.01, 15.  ])),
 (array([12, 28,  1,  0], dtype=int64),
  array([ 0.  ,  1.06,  5.01, 10.01, 15.  ]))]

第一个数组很有用,但其他数组没有任何好处-加上文本和方括号不是必需的。我尝试了np.delete np.tolist无济于事

任何帮助将不胜感激。

我是新手-如果代码效率低下,我们感到抱歉!

1 个答案:

答案 0 :(得分:0)

这是我对stackoverflow帖子的第一个答案。代替使用“ for循环”,请尝试使用更简单的“列表理解”。希望对您有帮助!

import numpy as np

# Random dataset. Create a list of 3 lists. Each list contains 20 random 
# numbers between 0 and 15.
Data = [np.random.uniform(0,15,20) for i in range(3)]

# Values used to bin the data.
Bins = [0, 1.06, 5.01, 10.01, 15]

# Using np.histogram on each list.
HistogramData = [np.histogram(i,Bins) for i in Data]

# 'i[0]' selects the first element in the tuple output of the histogram 
#  function i.e. the frequency. The function 'list()' removes the 'dtype= '.
BinnedData = [list(i[0]) for i in HistogramData]

print(BinnedData)

# Merging everything into a definition
def PrintHistogramResults(YourData, YourBins):
    HistogramData = [np.histogram(i,YourBins) for i in YourData]
    BinnedData = [list(i[0]) for i in HistogramData]
    print(BinnedData)

TestDefinition = PrintHistogramResults(Data, Bins)