Pandas: Iterate through a list of DataFrames and export each to excel sheets

两盒软妹~` 提交于 2019-12-06 07:42:20

It is easier to go from the string 'Data' to the value Data than the other way around. You can use locals()['Data'] to access the value associated to the variable whose string name is 'Data':

import pandas as pd

writer = pd.ExcelWriter("MyData.xlsx", engine='xlsxwriter')
seq = ['Data', 'ByBrand']
for name in seq:
    df = locals()[name]
    df.to_excel(writer, sheet_name=name)
writer.save()

locals() returns a read-only dictionary containing the current scope's local variables. globals() returns a dictionary containing the current scope's global variables. (Thus, if Data and ByBrand are defined in the global namespace rather than the local namespace, use globals() instead of locals().)


Another option is to collect the DataFrames in a dict. Instead of creating a variable for each DataFrame, make one dict, and let the keys be the sheet names and the values be DataFrames:

import pandas as pd

dfs = dict()
dfs['Data'] = ...
dfs['ByBrand'] = ...

writer = pd.ExcelWriter("MyData.xlsx", engine='xlsxwriter')
for name, df in dfs.items():
    df.to_excel(writer, sheet_name=name)
writer.save()

I think this is preferable since it does not require introspection tools like locals() or globals(). This second approach just uses a dict the way dicts are intended to be used: mapping keys to values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!