我有一個資料框字典,資料框基本上是檔案夾中的 csv 檔案。
所以我想將此函式應用于字典中的每個資料框:
def transformations(df):
row_1 = list(df.iloc[0])
row_1_upd = list(filter(None,row_1))
row_2 = list(df.iloc[1])
row_2_upd = list(filter(None,row_2))
new_cols = row_1_upd row_2_upd
list_df_col = list(df.columns)
for i in range(len(list_df_col)):
list_df_col[i]=new_cols[i]
df.columns = list_df_col
df = df.iloc[2:]
return df
我還能夠提取存盤在字典中的每個資料框的名稱:
filenames = os.listdir(r'C:\Users\xxxx\Python_Projects\Analytic_PBI') # lists all csv files in your directory
def extract_name_files(text): # removes .csv from the name of each file
name_file = text.strip('.csv')
return name_file
names_of_files = list(map(extract_name_files,filenames))
print(names_of_files)
['Analytic_2021_Actual_Budget_FTE', 'Analytic_2021_Actual_Budget_MarginDirectCost', 'Analytic_2021_Actual_Budget_OperationalHqOverheadsCost', 'Analytic_2022_Actual_FTE', 'Analytic_2022_Actual_MarginDirectCost', 'Analytic_2022_Actual_OperationalHqOverheadsCost', 'Analytic_2022_F1_U_FTE', 'Analytic_2022_F1_U_MarginDirectCost', 'Analytic_2022_F1_U_OperationalHqOverheadsCost']
所以我想做的是回圈使用字典 names_of_files
內部呼叫資料幀名稱的字典dataStorage
,并為每個資料幀應用函式:
for i, df in dataStorage.items():
df = dataStorage[names_of_files[i]]
df = transformations(df)
但我收到此錯誤:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [359], in <cell line: 1>()
1 for i, df in dataStorage.items():
----> 2 df = dataStorage[names_of_files[i]]
3 df = transformations(df)
TypeError: list indices must be integers or slices, not str
我知道我是否像這樣直接應用我的功能:
dataStorage["Analytic_2021_Actual_Budget_FTE"] = transformations(dataStorage["Analytic_2021_Actual_Budget_FTE"])
它有效,因為我測驗過。
我可能在這里過于復雜,但我對此的了解有限
uj5u.com熱心網友回復:
我認為你把事情復雜化了
for i, df in dataStorage.items():
df = dataStorage[names_of_files[i]]
df = transformations(df)
如果這個回圈的目標只是訪問df
,那么你根本不需要names_of_files
。以下應該也可以作業,因為您從回圈df
的標題中獲取for
for i, df in dataStorage.items():
#df = dataStorage[names_of_files[i]]
df = transformations(df)
您看到的錯誤是因為i
不是您從呼叫中獲得的索引enumerate
,而是dataStorage
字典的鍵(字串?),因此您不能使用它來索引您的names_of_files
串列。您可以將print
陳述句放在 for 回圈中以查看確切的內容i
和內容df
。不過,您不需要完成所有這些作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/505148.html
上一篇:按列填充表格