[英]How to export data in an excel file with specific column names from a dictionary?
I have made a dic like follow:我做了一个像下面这样的 dic:
number_of_c_in_level_ = dict()
for x in range(1,50):
number_of_c_in_level_[x]=x*2
How I can export those data in an excel file which has the column name as bellow如何将这些数据导出到列名如下的 excel 文件中
number_of_c_in_level_1 number_of_c_in_level_2 ... number_of_c_in_level_50
2 4 ... 100
or, please see an exemplar final excel file here或者,请在此处查看示例最终 excel 文件
You can make use of pandas
module to create a DataFrame(similar to excel) as per your need.您可以根据需要使用
pandas
模块创建一个 DataFrame(类似于 excel)。
DataFrame object in pandas module can accept dictionary object as an input and will convert into excel look a like structure. pandas 模块中的 DataFrame 对象可以接受字典对象作为输入,并将转换为 excel 看起来像结构。 See the below demo for better understanding..
请参阅下面的演示以更好地理解..
import pandas as pd # module required for the DataFrame operations
print(number_of_c_in_level_)
{1: 2, 2: 4, 3: 6, ...., 48: 96, 49: 98}
Before converting into DataFrame, change the dictionary key : values
as required in the output.在转换为 DataFrame 之前,根据输出中的要求更改字典
key : values
。
Note: Dictionary values should be in the form of array(Lists) to get a expected DataFrame.注意:字典值应该是数组(列表)的形式以获得预期的数据帧。
Req_Change = {"number_of_c_in_level_"+str(i):[j] for i,j in number_of_c_in_level_.items()}
The above code makes the required column name format and the values in the form of arrays.上面的代码制作了需要的列名格式和数组形式的值。
print(Req_Change)
{'number_of_c_in_level_1': [2], .... , 'number_of_c_in_level_49': [98]}
Now we can convert this Dictionary into DataFrame with the below step,现在我们可以通过以下步骤将此字典转换为数据帧,
Export = pd.DataFrame(df)
print(Export)
number_of_c_in_level_1 number_of_c_in_level_2 ... number_of_c_in_level_49
2 4 98
Finally lets Export the DataFrame into Excel / csv,最后让我们将 DataFrame 导出到 Excel / csv,
Note: To Export into Excel, you might need openpyxl
module.注意:要导出到 Excel,您可能需要
openpyxl
模块。 So you can export into csv and change it into Excel format later所以你可以导出成csv,以后再改成Excel格式
Export.to_excel("Export.xlsx",index=False)
Export.to_csv("Export.csv",index=False)
You can simply put the text in the key part of the dictionary, convert to a dataframe and then write it to CSV or Excel (I recommend CSV because it is a more universal format).您可以简单地将文本放在字典的关键部分,转换为数据框,然后将其写入 CSV 或 Excel(我推荐 CSV,因为它是一种更通用的格式)。 Here is your code edited to the version:
这是您编辑到版本的代码:
import pandas as pd
number_of_c_in_level_ = dict()
for x in range(1,51):
number_of_c_in_level_['number_of_c_in_level_' + str(x)] = 2*x
df = pd.DataFrame(number_of_c_in_level_, index=[0])
with open('result2.csv','w') as csv_file:
df.to_csv(csv_file,index=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.