我有多个 dict 列表收敛到一个 dict 列表到一个 excel 文件。这个想法是为每个字典、键(web1、web2)、名称制作一个excel表,并在每张表中包含正确的信息。
下面代码的问题是它制作了一张一张的excel文件。
关于我应该怎么做的任何想法?
import pandas as pd
web1 = [{
'country': 'NL',
'id': '56655',
'title': 'some 1',
'date': 'today',
'description': 'something else here',
'web': 'http://'
},
{
'country': 'IE',
'jobid': '45862',
'title': 'some 2',
'date': 'today',
'description': 'something else here',
'web': 'http://'
}]
web2 = [{
'country': 'IT',
'id': '77878',
'title': 'some 3',
'date': 'today',
'description': 'something else here',
'web': 'http://'
},
{
'country': 'NE',
'id': '45862',
'title': 'some 4',
'date': 'today',
'description': 'something else here',
'web': 'http://'
}]
data =[{
'website1': web1
},
{
'website1': web2
}]
for x in data:
z = str(*x).capitalize()
for y in x.values():
cx = pd.DataFrame(y, columns = ['country', 'title', 'date', 'id', 'web','description'])
writer = pd.ExcelWriter('test.xlsx')
cx.to_excel(writer, sheet_name=f'{z}')
workbook = writer.book
worksheet = writer.sheets[f'{z}']
align_r = workbook.add_format({'align': 'right'})
bold = workbook.add_format({'bold': True})
color_format = workbook.add_format({'bg_color': 'green'})
condi_color = worksheet.conditional_format('G:G', {
'type': 'text',
'criteria': 'containing',
'value': 'red',
'format': color_format})
# set column spacing, format
worksheet.set_column('A:A', 3)
worksheet.set_column('B:B', 2, bold)
worksheet.set_column('C:C', 40, bold)
worksheet.set_column('D:D', 10, align_r)
worksheet.set_column('G:G')
writer.save()
最佳答案
pandas
有一个 ExcelWriter
助手,它在文档中是正确的。
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html
>>> writer = pd.ExcelWriter('output.xlsx')
>>> df1.to_excel(writer,'Sheet1')
>>> df2.to_excel(writer,'Sheet2')
>>> writer.save()
因此,每个 dict 都变成了一个带有
pd.DataFrame(webN)
的 df然后你用 writer 调用 df,如上面的第 2 行和第 3 行所示。编辑:
要遍历您的 dicts 列表,您可以编写:
writer = pd.ExcelWriter('output.xlsx')
for i in range(len(list_of_dicts)):
df = pd.DataFrame(list_of_dicts[i]) # Construct the dataframe
df.to_excel(writer, "Sheet{}".format(i + 1))
根据您可能想要使用 from_dict 构建数据框的数据
关于python - Pandas 多个 excel 表中的 dict 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53011321/