簡體   English   中英

在 for 循環中附加帶有新鍵和值的字典

[英]Appending dictionary with new keys and values in for loop

我目前正在嘗試循環通過 dataframe 進行線性回歸。 每次迭代后,我想保存當前列名和生成的 Adj。 字典中的 R 平方值:

import statsmodels.api as sm

for columns in [x for x in var_sel.columns if x != 'price']:
    
    fit_d = {}
    
    Y = var_sel['price']

    X = var_sel[columns]

    X = sm.add_constant(X)

    model = sm.OLS(Y,X, missing = 'drop').fit()
    
    fit_d[columns] = model.rsquared

但是當我打印字典時,它只輸出{'room_type_Shared room': 0.0003039648861731248}這是 dataframe 的最后一列。 我如何 append 字典與每個迭代結果?

您必須在 for 循環之外聲明字典。 在上面的代碼中,每次循環運行時都會重新聲明字典。

import statsmodels.api as sm

fit_d = {}

for columns in [x for x in var_sel.columns if x != 'price']:
    
    Y = var_sel['price']

    X = var_sel[columns]

    X = sm.add_constant(X)

    model = sm.OLS(Y,X, missing = 'drop').fit()
    
    fit_d[columns] = model.rsquared

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM