我有一个字典,其中包含“ data.csv”中每个状态的数据框。
df=pd.read_csv('data.csv')
dict_of_st = {k: v for k, v in df.groupby('Preferred State/Province')}
我想将每个数据帧写入到已经存在的工作簿(“ test.xlsx”)中的单独的excel工作表中。
我尝试使用for循环和load workbook
from openpyxl import load_workbook
book = load_workbook('test.xlsx')
writer = pd.ExcelWriter('test.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
for i in dict_of_st:
i.to_excel(writer, sheet_name=i)
writer.save()
但是jupyter笔记本电脑会引发此错误:
AttributeError Traceback (most recent call last)
<ipython-input-8-c1ba1b4d53d8> in <module>
7
8 for i in dict_of_st:
----> 9 i.to_excel(writer, sheet_name=i)
10
11 writer.save()
AttributeError: 'str' object has no attribute 'to_excel'
答案 0 :(得分:3)
for x in some_dict
遍历键。您应该在items()
上进行显式迭代,以返回键值对:
for df_name, df in dict_of_st.items():
df.to_excel(writer, sheet_name=df_name)