[英]How to extract the name of a dataframe from a list and print it as a heading to the output?
group_high
, group_medium
, group_low
, group_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):
您可以決定在字典中收集所有 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.