簡體   English   中英

Pandas。 如何從數據框列表中調用數據框?

[英]Pandas. How to call data frame from the list of data frames?

我有一個數據框列表:

all_df = ['df_0','df_1','df_2','df_3','df_4','df_5','df_6']

我怎樣才能從這個列表中調用他們來做這樣的事情:

for (df,names) in zip(all_df,names):
   df.to_csv('output/{}.csv'.format(names))

預期執行時,我收到錯誤'str' object has no attribute 'to_csv'因為我將字符串提供給'to_csv'

如何在for循環中保存多個數據幀(或對它們執行其他操作)?

謝謝!

您能否還提供一個關於如何從中創建“正確”數據框列表的想法:

path = 'inp/multysheet_excel_01.xlsx'
xl = pd.ExcelFile(path)
sh_name = xl.sheet_names

n = 0
for i in sh_name:
    exec('df_{} = pd.read_excel("{}", sheet_name="{}")'.format(n, path, i))
    n+=1

so basically I'm trying to get the each sheet of an input excel as a separate dataframe, perform some actions on them, and save each output dataframe in separate excels.

你很接近,但我在那個 for 循環中看到了一些錯誤。 假設您有一個數據框列表dfs ,並將其對應的名稱作為字符串names列表,您可以使用以下名稱將這些數據框保存為:

dfs = [df_1, df_2, df_3]
names = ['df_0','df_1','df_2']

for df,name in zip(dfs,names):
    df.to_csv('output\\{}.csv'.format(name))

雖然如果您只有一個名稱列表,您也可以執行以下操作:

names = ['df_0','df_1','df_2']
for name in names:
    globals()[name].to_csv('output\\{}.csv'.format(name))

暫無
暫無

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

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