简体   繁体   English

在 python 中使用 .to_excel 写字典到 excel

[英]Writing a dictionary to excel using .to_excel in python

I have a dictionary with a couple floats, an int and a series all in one.我有一本字典,里面有几个浮点数、一个整数和一个系列。 I would like to write this to Excel all on the same sheet.我想把这个写到 Excel 都在同一张纸上。

series = df5.copy()

dictionary = {'Avg':2.3534, 'Expected':series, 'Variance':1.01, 'Std. Dev': 1.78, '# of broken parts':300}

I have tried two different ways of writing these to Excel, one being straight to Excel where I receive an error saying dict has no.to_excel functionality, and the other method I tried the following:我尝试了两种不同的方式将这些写入 Excel,一种是直接写入 Excel,在那里我收到一条错误消息,说 dict 没有.to_excel 功能,另一种方法我尝试了以下方法:

dictionary.to_excel(writer,sheet_name = 'Break Date', index = False)

or

for key in dictionarys.keys():
    dictionary[key].to_excel(writer,sheet_name = key, index = False)

I would like the keys of the dictionary to be the title of the columns.我希望字典的键成为列的标题。

Desired output in Excel on same sheet:在同一张纸上的 Excel 中需要 output:

Average  Expected   Variance    Std. Dev    # of broken parts
2.3534     2           1.01       1.78          300
           4
           2
           4

You can use the pandas library to convert your dictionary to a DataFrame and then write it to an Excel sheet.您可以使用 pandas 库将字典转换为 DataFrame,然后将其写入 Excel 工作表。

First, convert the dictionary to a DataFrame:首先,将字典转换为 DataFrame:

df = pd.DataFrame(dictionary)

Then, use the to_excel method to write the DataFrame to an Excel sheet:然后,使用to_excel方法将DataFrame写入Excel表:

df.to_excel(writer, sheet_name='Break Date', index=False)

This will write the DataFrame to the sheet 'Break Date' in your Excel file, with the keys of the dictionary as the column names.这会将 DataFrame 写入 Excel 文件中的工作表“Break Date”,并将字典的键作为列名。

If you want to export all the key-value of the dictionary to the same sheet, you could use the following code:如果要将字典的所有键值导出到同一张表中,可以使用以下代码:

df = pd.DataFrame.from_dict(dictionary, orient='index').transpose()
df.to_excel(writer, sheet_name='Break Date', index=False)

This will create a DataFrame where the keys of the dictionary are the columns name and the values of the dictionary are the values of the DataFrame and then export it to the excel sheet.这将创建一个 DataFrame,其中字典的键是列名,字典的值是 DataFrame 的值,然后将其导出到 excel 工作表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM