【问题标题】:Python: How to perform function on multiple files and combine resultsPython:如何对多个文件执行功能并组合结果
【发布时间】:2013-10-15 08:35:06
【问题描述】:

我正在尝试创建一个比较来自多个文件的数据的函数。这些文件是通过一个对话框窗口选择的(来自 GUI 平台 Tkinter)

def compare_datafiles(file_name): 
    data = np.genfromtxt(file_name, dtype=float, delimiter=',', skiprows=(2), usecols=(1,2,3,4,5,6), skip_footer=(3))
    initial = data[0,:]
    final = data[-1,:]
    weightDiff=final-initial  
    data=np.row_stack((data, weightDiff)) 
    totalWD=sum(data[4,:]) # calculate total weight
    distr=np.round((weightDiff/totalWD),2) 
    print distr
    return  distr   

for x in selectedFiles:
        M = compare_datafiles(x)

当我使用两个输入文件运行该函数时,它会打印两个数组:

runfile(r'C:\Users...)
    [ 0.23  0.04  0.1   0.14  0.12  0.38]
    [ 0.22  0.05  0.13  0.16  0.12  0.32]

但只返回其中一个:

M
array([ 0.22,  0.05,  0.13,  0.16,  0.12,  0.32])

如何让它返回两个数组?

【问题讨论】:

    标签: python arrays file function compare


    【解决方案1】:

    在你的代码中,你写:

    for x in selectedFiles:
        M = compare_datafiles(x)
    

    您在每个循环中重新分配给M,因此只存储最后一个值。您可以将 M 设为列表并附加到它,或者使用列表推导:

    >>> M = [compare_datafiles(x) for x in selectedFiles]
    

    【讨论】:

    • 谢谢你,@miku。您能否建议一种简单的方法,将从函数中获得的数据绘制为单独的数组?
    • 我是这样做的:arrayNumber = range(0,len(selectedFiles)) for x in arrayNumber: plt.plot(sizes,M[x],'-rs',markerfacecolor='none', linewidth='2')
    • python 有很多绘图库,例如matplotlib.org, github.com/yhat/ggplot, gnuplot-py.sourceforge.net -
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 2022-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多