Numpy 배열 인쇄 [닫기]

Nov 03 2020

이전 계산 결과를 인쇄하려고하는데 Numpy를 사용하여 배열에서 값을 올바르게 인쇄하는 데 문제가 있습니다. 루프의 각 변수는 이전의 계산에 의해 정의되었으며 각 속도에 대한 데이터를 .5kn 단위로 가져 오려면 속도 순열을 통해 실행해야합니다.

문제의 코드는 다음과 같습니다.

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]),)

답변

AdamKern Nov 03 2020 at 22:39

좋아, 여기에 목표가 무엇인지 이해한다고 생각한다. 당신이 가진 것은 1D 배열의 전체 묶음입니다-각각은 벡터를 나타냅니다 (행렬 또는 텐서와 비교하여). 귀하의 목표는 매우 구체적인 방식으로 표에 이러한 값을 인쇄하는 것입니다. 빠른 수정은 print(kFrm, end="")다른 모든 인쇄물과 동일한 규칙을 사용 하도록 변경 하는 것 같습니다 print('{:12.4f}'.format(kFrm[i]), end='').. np.set_printoptions()그 후에 전화를 끊으십시오 .

왜 이런 일이 발생합니까? 현재 코드가 부분적으로 이전 대화를 기반으로한다고 생각하지만 전체 컨텍스트가 없었습니다. kFrm는 작업중인 다른 모든 변수와 마찬가지로 벡터이므로 i'th해당 행에 해당 벡터 의 값 을 인쇄하기 만하면 됩니다. 단일 행으로 전체 벡터를 인쇄하고 싶어했다면, 다음 은 바로 지금처럼 당신은 코드를 사용하십시오.

참고로 pandas 를 사용하면 두통을 줄일 수 있습니다 (또는 더 많은 두통을 유발할 수 있음) . 그렇게한다면 아래와 같이 할 수 있습니다. 유일한 캐치는 당신이 당신의 제 1 및 제 2 열 이름을 그래서 당신이 열에게 같은 일을 이름을 수 없다는 것입니다 V하고 VS, 대신 VV:

# 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일을 잘 인쇄 할 작업 엄청난 양의 일을했다. 우리가 그 작업을 더 많이 활용할수록 우리의 출력이 견고하고 정말 좋아 보일 것이라는 확신이 더 커집니다. 그러나이 답변의 후반부를 무시하기로 결정할 수도 있으며 실제로는 당신에게 반대하지 않을 것입니다.