首页 > 解决方案 > 将循环的 numpy 直方图输出导出到没有数组信息和格式的列表

问题描述

我正在运行从多个列表编译的数据循环。我最终将创建一个直方图,但是我希望将直方图函数的分箱输出导出到列表中。目前,数据被导出一个列表,看起来像一个数组 - 我假设这来自 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 无济于事

任何帮助将非常感激。

我很新 - 如果代码效率低下,我很抱歉!

标签: python-3.xnumpyscipyhistogramtolist

解决方案


这是我对 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)

推荐阅读