【问题标题】:How to extract the name of a dataframe from a list and print it as a heading to the output?如何从列表中提取数据框的名称并将其作为标题打印到输出?
【发布时间】:2020-08-26 17:31:44
【问题描述】:

My list1 包含 4 个数据框,例如:

group_highgroup_mediumgroup_lowgroup_rba

我创建了一个 for 循环,以便每个数据帧进入循环并提供输出。

在打印输出之前,我希望我的代码将数据框名称作为标题,以便我能够识别结果属于哪个数据框。

示例:在打印group_high 数据帧结果之前,我希望有一个标题为group_high,然后是group_high 的输出。同样,我需要它用于list1 中的所有其他数据帧。

下面是我的代码:

os.chdir(r'C:\Users\91979\Downloads\head code\src')
from classStruct.model import model
list1 = [group_high,group_medium,group_low,group_rba]
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)
    print(pd.DataFrame(clustSet[clustSet['Rejection (%)Predicted'] == clustSet['Rejection (%)Predicted'].min()]))
    print('\n')
    print('\n')

【问题讨论】:

  • 数据框不存储self.name...您需要自己提供类似for i, name in zip(list1, names_list):的内容
  • @RichieV 如果我有一个单独的 list2 包含在打印输出之前我想要的所有标题。我应该在我的代码的哪一部分插入它? list2 = ["Group High", "Group Medium", "Group Low", Group RBA"
  • 我想我需要做类似for j in list2: print j 的事情,但我应该在代码的哪一部分做。
  • 你看到我的回答了吗? names_list 在我的代码中是你的 list2... 习惯在这种情况下使用 dicts,甚至在可能的情况下使用完整的 df
  • @RichieV 我得到了输出,但代码给出了 16 个结果,而我只需要 4 个。只有前 4 个输出。从 5 日到 16 日,它是前 4 个输出的副本。我怎样才能删除它们? list1 = [group_high,group_medium,group_low,group_rba] names_list = ["Group High:", "Group Medium:", "Group Low:", "Group RBA:"] for i, name in zip(list1, names_list): all_dfs = {name: df for name, df in zip(names_list, list1)} for name, df in all_dfs.items(): print(name) 如果打印此代码,它会给出 16 个名称,但我只需要 4 个。你能帮帮我吗

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


【解决方案1】:

Dataframes 不存储 self.name... 你需要自己提供类似的东西

for i, name in zip(list1, names_list):

您可以决定在字典中收集所有 dfs

all_dfs = {name: df for name, df in zip(names_list, list1)}
# then iterate
for name, df in all_dfs.items():

通常,如果多个 dfs 具有相同的列并且索引具有相同的级别,最好将它们保留为单个 df 并使用 df.groubpy 迭代分组的行(因为您的 dfs 似乎来自groupby 无论如何你可以跳过你可能分成几个 dfs 并直接从 groubpy 迭代的步骤,如果是你的情况)。

# if dfs come from different sources
# concatenate them into a single df
df_main = pd.concat(
    list1, # collection of dfs to be concatenated
    keys=names_list, # names for dfs, will be appended as the outermost index level
    names=['name_of_df'] # name for the level that will be appended
)

# iterate over a groupby object
for name_of_df, df_sub in df_main.groubpy('name_of_df'):
    # name_of_df: string provided in `names_list`
    # df_sub: filtered df

编辑:

请理解以上所有代码块都是专有的,即选择一种解决方案并坚持使用。您的评论试图结合不同的解决方案,并在此基础上使用 all_dfs.items(),这不在提供的任何选项中,对于这种情况也不是必需的。

如果你选择第一个选项,那么

for i, name in zip(list1, names_list):
    print(name)
    needed_cols = i.columns # from your code
    # the rest of your code inside the loop
    

【讨论】:

    猜你喜欢
    • 2019-10-31
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    相关资源
    最近更新 更多