打印一个Numpy数组 [英] Printing a Numpy Array

查看:41
本文介绍了打印一个Numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打印一些先前计算的结果,并且在使用Numpy将值正确打印出数组时遇到了一些问题.循环中的每个变量都是由先前的计算定义的,它需要遍历速度排列才能以.5kn的增量获取每种速度的数据.

I am trying to print the results of some previous calculations, and am having some issues using Numpy to print the values out of an array correctly. Each of the variables in the loop is defined by calculations previously, and it needs to run thru the speed permutations to get the data for each speed in .5kn increments.

有问题的代码是:

print('Speed Dependent factors and residuary resistance coefficents')
    #output table
    #table header
        #Top Row
    
    print('V'.center(12),end='')   #the end='' prevents a new line'
    print('V'.center(12),end='')
    print('FN'.center(12),end='') 
    print('CRstdmin'.center(12),end='') 
    print('kFrmin'.center(12),end='')
    print('CRBTmin'.center(12),end='')
    print('CRmin'.center(12),end='')
    print('CRstdmean'.center(12),end='')
    print('kFrmean'.center(12),end='')
    print('CRBTmean'.center(12),end='')
    print('CRmean'.center(12),)
        #Second Row
    print('knots'.center(5),end='')
    print('m/s'.center(12), end='')
    print('--'.center(12), end='')
    print('--'.center(12), end='')
    print('--'.center(12), end='')
    print('--'.center(12), end='')
    print('10^-3'.center(12), end='')
    print('--'.center(12), end='')
    print('--'.center(12), end='')
    print('--'.center(12), end='')
    print('10^-3'.center(12))
    print('-'*135)

    #loop for table cell values
    kFrmin=round(kFrmin,5)

    for i in range(len(VS)):
        print('{:12.1f}'.format(Vskn[i]), end='')
        print('{:12.3f}'.format(VS[i]), end='')
        print('{:12.4f}'.format(FN[i]), end='') 
        print('{:12.4f}'.format(CRstdmin[i]), end='')
        print('{:12.4f}'.format(kFrmin), end='')
        print('{:12.4f}'.format(CRBTmin[i]), end='')
        print('{:12.4f}'.format(CRmin[i]), end='')
        print('{:12.4f}'.format(CRstdm[i]), end='')
        print(kFrm, end="")
        np.set_printoptions() 
        #print('{:12.4f}'.format(kFrm), end='')
        print('{:12.4f}'.format(CRBTm[i]), end='')
        print('{:12.4f}'.format(CRm[i]),)

推荐答案

好的,好的,我想我明白这里的目标是什么.您拥有的是一堆完整的一维数组-意味着每个数组都代表一个向量(与矩阵或张量相比).您的目标是以一种非常特定的方式在表中打印这些值.在我看来,快速的解决方法是更改​​ print(kFrm,end =")以使用与所有其他打印相同的约定: print('{:12.4f}'.format(kFrm [i]),end ='').在此之后摆脱 np.set_printoptions()调用.

Right, ok, I think I understand what the goal is here. What you have are a whole bunch of 1D arrays - meaning each represents a vector (as compared to a matrix or tensor). Your goal is to print those values in a table in a very specific way. It seems to me that the quick fix is to change print(kFrm, end="") to use the same convention as all the other prints: print('{:12.4f}'.format(kFrm[i]), end=''). Get rid of the np.set_printoptions() call after that.

为什么会这样?我相信您当前的代码部分基于先前的对话,但这没有完整的上下文.与正在使用的所有其他变量一样, kFrm 是向量,因此您只想在该行中打印该向量的 thth 值.如果您想将整个矢量打印为一行,请然后使用现在的代码.

Why is this happening? I believe your current code is partially based on a previous conversation, but that was without the full context. kFrm is a vector just like all of the other variables you're working with, so you just want to print the i'th value of that vector in that row. If you had wanted to print the entire vector as a single row, then you'd use the code as it is right now.

作为旁注,您可以使用

As a side note, you may be able to save yourself some headache (or, arguably, introduce more of a headache) by using pandas. If you do, you could do something like below. The only catch is that you can't name columns the same thing, so you have to name your first and second columns V and VS, instead of V and V:

# At the top of your file
import pandas as pd

# All the other stuff
...

kFrmin = round(kFrmin,5)

# Create the data frame,
# mapping name to vector.
# Each entry here represents
# a column in the eventual output
dataframe = pd.DataFrame({
    "V": Vskn,
    "VS": VS,
    "FN": FN,
    "CRstdmin": CRstdmin,
    "kFrmin": float(kFrmin),  # kFrmin is defined as an int in your
    "CRBTmin": CRBTmin,       # code, we need a float
    "CRmin": CRmin,
    "CRstdmean": CRstdm,
    "kFrmean": kFrm,
    "CRBTmean": CRBTm,
    "CRmean": CRm,
})

# Set some options for printing
with pd.option_context(
    "display.max_columns", 11,  # Display all columns
    "display.expand_frame_repr", False,  # Don't wrap columns
    "display.float_format", "{:>12.4f}".format,  # Default to 4 digits of precision,
):                                               # pad to 12 places
    df_str = dataframe.to_string(
        index=False,  # Don't print the dataframe index
        formatters={
            "V": "{:>12.1f}".format,  # V uses 1 digit of precision
            "VS": "{:>12.3f}".format, # VS uses 3 digits of precision
        }
    )

# Everything from here... (see below)
df_str_rows = df_str.split("\n")  # Split up the original table string

# Create the unit row values
unit_row = ["knots", "m/s", "--", "--", "--", "--", "10^-3", "--", "--", "", "10^-3"]
# Pad them using right justification
pd_cspace = pd.get_option("column_space")
unit_row_str = (unit_row[0].rjust(pd_cspace) + 
                ''.join(r.rjust(pd_cspace + 1) for r in unit_row[1:]))

# Insert that new row back into the table string
df_str_rows.insert(1, unit_row_str)
df_str_rows.insert(2, "-" * len(unit_row_str))
df_str = '\n'.join(df_str_rows)
# ... to here was just to include the extra unit row
# and the dash line separating the table. You could ignore
# it if you don't care about those

# Ok now print
print('Speed Dependent factors and residuary resistance coefficents')
print(df_str)

这给您:

Speed Dependent factors and residuary resistance coefficents
           V           VS           FN     CRstdmin       kFrmin      CRBTmin        CRmin    CRstdmean      kFrmean     CRBTmean       CRmean
       knots          m/s           --           --           --           --        10^-3           --           --           --        10^-3
----------------------------------------------------------------------------------------------------------------------------------------------
        15.0        7.717       0.1893       0.8417       1.0000       0.1870       0.7645       0.8417       1.0000       0.1786       0.7302
        15.5        7.974       0.1956       0.8928       1.0000       0.1984       0.8110       0.8928       1.0000       0.1895       0.7746
        16.0        8.231       0.2019       0.9502       1.0000       0.2111       0.8631       0.9502       1.0000       0.2017       0.8243
        16.5        8.488       0.2083       1.0138       1.0000       0.2253       0.9208       1.0138       1.0000       0.2152       0.8795
        17.0        8.746       0.2146       1.0837       1.0000       0.2408       0.9843       1.0837       1.0000       0.2300       0.9401
        17.5        9.003       0.2209       1.1598       1.0000       0.2577       1.0535       1.1598       1.0000       0.2461       1.0062
        18.0        9.260       0.2272       1.2422       1.0000       0.2760       1.1283       1.2422       1.0205       0.2690       1.0997
        18.5        9.517       0.2335       1.3308       1.0000       0.2957       1.2088       1.3308       1.0508       0.2968       1.2132
        19.0        9.774       0.2398       1.4257       1.0000       0.3168       1.2950       1.4257       1.0829       0.3276       1.3394
        19.5       10.032       0.2461       1.5269       1.0000       0.3393       1.3869       1.5269       1.1167       0.3619       1.4793
        20.0       10.289       0.2524       1.6343       1.0000       0.3631       1.4845       1.6343       1.1525       0.3997       1.6340

为什么用 pandas 来解决所有这些麻烦?我认为我们这样做是因为 pandas numpy 已经做了很多工作,以使打印效果很好.我们可以利用这项工作的能力越强,我们就越有信心我们的输出将是可靠的并且看起来确实不错.但是,您也可以决定忽略此答案的后半部分,我真的不会反对您.

Why go through all of this trouble with pandas? I'd argue we do so because pandas and numpy have done a massive amount of work to make things print nicely. The more we can leverage that work, the more confident we can be that our output will be robust and really look good. However, you could also decide to ignore the second half of this answer and I really wouldn't hold it against you.

这篇关于打印一个Numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆