【问题标题】:How to set up a heading before an output is printed in a for loop in python?如何在python的for循环中打印输出之前设置标题?
【发布时间】:2020-08-27 01:44:32
【问题描述】:

我在list1 中有 4 个df

df1df2df3df4

list1 中的每个数据帧都进入一个 for 循环并提供单个输出,但在打印输出之前,我希望给出一个标题,以便我能够识别输出属于哪个组。即它是属于高、低、中还是平均

list2 具有需要为 4 个输出提供的所有标题。 list2 = ["High","Medium","Low","Average"]

例子:

     Before df1 output is printed i wanted the heading to be 'High'

     Before df2 output is printed i wanted the heading to be 'Medium'

     Before df3 output is printed i want the heading to be printed as 'Low'

     Before df4 output is printed i want the heading to be printed as 'Average'

下面是我的代码:

import os
os.chdir(r'C:\Users\91979\Downloads\head code\src')
from classStruct.model import model
list1 = [df1,df2,df3,df4]
list2 = ["High","Medium","Low", "Average"]
for i in list1:
    needed_cols = i.columns
    target_col =  ['Rejection (%)']
    cols = list(set(needed_cols) - set(target_col))
    totData = i
    totData = totData.round(decimals=2)
    Model1 = model(totData,cols,['Rejection (%)'])
    clustSet = pd.DataFrame([C.clusterCenter for C in Model1.clustersList])
    Model1.predictor(clustSet, ["Rejection (%)"], Normalize=False)
    Model1.optimalClusterRejectionSeries = round(min(clustSet['Rejection (%)Predicted']),4)
    col_list = ['GCS (kg/cm2)', 'Inert Fines (%)', 'Volatile Matter (%)',
       'LOI (%)', 'Active Clay (%)', 'GFN/AFS (no)', 'Compactability (%)',
       'Wet Tensile Strength (gm/cm2)', 'Moisture (%)',
       'Permeability (no)', 'Temp. of Sand after mix.(C)']
    Model1.deNormalizeColumns(col_list, clustSet).to_csv("Predicted_optimal.csv")
    Model1.deNormalizeColumns(col_list, clustSet)

    
    for j in list2:
        print(j)
    print(pd.DataFrame(clustSet[clustSet['Rejection (%)Predicted'] == clustSet['Rejection (%)Predicted'].min()]))
    print('\n')
    print('\n')

我应该在代码的哪一部分打印list2 中的标题,以便获得正确的 4 次迭代和正确的标题。

【问题讨论】:

    标签: python python-3.x pandas python-2.7


    【解决方案1】:

    你可以使用 zip:

    list1 = [df1,df2,df3,df4]
    list2 = ["High","Medium","Low", "Average"]
    for i, j in zip(list1, list2):
        print('Before output is printed i wanted the heading to be %s' % j)
        print('This is the dataframe %s' % i)
    

    然后您可以在打印标头后稍后在循环中打印您的数据帧i

    样本头输出:

    Before output is printed i wanted the heading to be High
    This is the data frame df1
    Before output is printed i wanted the heading to be Medium
    This is the data frame df2
    Before output is printed i wanted the heading to be Low
    This is the data frame df3
    Before output is printed i wanted the heading to be Average
    This is the data frame df4
    

    【讨论】:

    • 非常感谢。它工作:) 感谢您的时间
    • @Thanuja 欢迎您。一个更好的方式来感谢 SO 是 upvote :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    相关资源
    最近更新 更多