我無法將我所做的更改應用于字典中的資料框。更改是通過 for 回圈完成的。
問題是,雖然回圈作業是因為單個迭代的 df 進行了更改,但它們不適用于它們所在的字典。最終目標是創建所有資料幀的合并,因為它們來自不同的 Excel 作業表和作業表。這里的代碼:
匯入兩個 excel 檔案,將 None 分配給 Sheet_Name 引數,以便將檔案的所有作業表匯入 dict。我在 EEG excel 檔案中有 8 張,在 SC 檔案中有 5 張
import numpy as np impody pandas as np eeg = pd.read_excel("path_file", sheet_name = None) sc = pd.read_excel("path_file" sheet_name = None)使用 update 方法將第一個字典與第二個字典合并。現在 EEG dict 包含 EEG 和 SC。所以現在我有一個里面有 13 df 的字典
eeg.update(sc)為了在單個 df 中進行一些修改,需要回圈 for。將索引重置為特定列(在所有 df 上通用),更改其名稱,在與 df 的鍵對應的變數上添加前綴,最后用 nan 更改 0。
for key, df in eeg.items(): df.set_index(('Unnamed: 0'), inplace = True) df.index.rename(('Sbj'), inplace = True) df = df.add_prefix( key '_') df.replace (0, np.nan, inplace = True)
盡管在字典項上設定了回圈并且單個迭代資料框有效,但我沒有看到字典 df 上的更改,因此無法繼續將它們提取到串列中,然后合并。
正如您在圖 1 中看到的那樣,for 回圈中的單個 df 很好!
但是當我去字典中的 df 時,它們仍然像以前一樣結果。
uj5u.com熱心網友回復:
您需要將修改后的資料框映射回您的字典:
for key, df in eeg.items():
df.set_index(('Unnamed: 0'), inplace = True)
df.index.rename(('Sbj'), inplace = True)
df = df.add_prefix( key '_')
df.replace (0, np.nan, inplace = True)
eeg[key] = df #map df back into eeg
你可能想要的是:
# merge the dataframes in your dictionary into one
df1 = pd.DataFrame()
for key, df in eeg.items():
df1 = pd.concat([df1,df])
# apply index-changes to the merged dataframe
df1.set_index(('Unnamed: 0'), inplace = True)
df1.index.rename(('Sbj'), inplace = True)
df1 = df1.add_prefix( key '_')
df1.replace (0, np.nan, inplace = True)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/444920.html
上一篇:Pandas為系列添加靜態日期
