簡體   English   中英

無法在循環中使用 df.merge 更新 pandas 數據幀 - 缺少什么?

[英]Unable to update pandas dataframes with df.merge in a loop - what am missing?

我正在嘗試使用存儲在 dataframe 中的一些計算結果來更新一組 pandas 數據幀。 我創建了以下循環來執行此操作。 這似乎在循環內工作,但我發現原來的 dataframe 在循環完成后沒有更新!

請你能告訴我哪里出錯了嗎? 我在 Windows 10 機器上使用python 3.7.1pandas 1.0.5

z_score_list = ['LVESV_i', 'LVEDV_i', 'LVSV_i', 'LV_mass_i', 'RVEDV_i', 'RVESV_i', 'RVSV_i'] # columns used for calcuation
df_list = [t1df, t1vsd_df, t1highshunt_df, t1preTVcases_df] #list of dfs to update
print('Before loop shape: ', t1df.shape)
for i, df in enumerate(df_list):
    print('before update =', df.shape)
    df_z = df[z_score_list]
    df_z = calc_Z_scores(df_z,merge=False) # function returns calculated Z-scores in a dataframe
    df = df.merge(df_z, on = df.index, how='inner') # here I merge them
    df.drop(columns = 'key_0', inplace=True) # drop the additional index
    # df.head()
    print('after update = ', df.shape)
    del(df_z)
    # df = df.copy(deep=True) - tried this, but does not work

print('After loop shape: ', t1df.shape)

這是 output:

Before loop shape:  (63, 55)
before = (63, 55)
after =  (63, 62)
before = (8, 55)
after =  (8, 62)
before = (30, 54)
after =  (30, 61)
before = (55, 55)
after =  (55, 62)
After loop shape:  (63, 55)

我認為在有此評論“# here I merge them”的行上,您正在從合並中獲得一個新的引用,並將其分配給 df 引用,這是對 t1df 的引用丟失的地方。 嘗試在該行使用 hash function 就地合並或打印 df 的地址/哈希,然后查看。

暫無
暫無

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

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