[英]How can we do the process of appending excel from dictionary?
I am trying to write a code to parse some data from network output with a loop on set of devices and append the results in a dictionary and then write each dictionary keys and values into an excel sheet我正在尝试编写一个代码来解析来自网络输出的一些数据,并在一组设备上循环并将结果附加到字典中,然后将每个字典键和值写入 Excel 表
The problem I am facing at the moment that the key values are printed as column headers every time the loop is executed我目前面临的问题是每次执行循环时键值都打印为列标题
dictionary = {"key1":[],"key2":[],"key3":[]}
dictionary["key1"].append(parse_value1)
dictionary["key2"].append(parse_value2)
dictionary_to_df = pd.DataFrame(dictionary)
dictionary_to_df("csv path,mode = "a",index = False, header = True)
output is something like that:输出是这样的:
key1![]() |
key2![]() |
key3![]() |
---|---|---|
value1![]() |
value2![]() |
value3![]() |
key 1![]() |
key2![]() |
key3![]() |
value4![]() |
value5![]() |
value6![]() |
however I would like to get the output as below但是我想得到如下输出
key1![]() |
key2![]() |
key3![]() |
---|---|---|
value1![]() |
value2![]() |
value3![]() |
value4![]() |
value5![]() |
value6![]() |
use simple code (pd.DataFrame.from_dict):使用简单的代码(pd.DataFrame.from_dict):
dictionary = {"key1":[],"key2":[]}
parse_value1=["value1","value2","value3"]
parse_value2=["value4","value5","value6"]
dictionary["key1"].extend(parse_value1)
dictionary["key2"].extend(parse_value2)
dictionary_to_df =pd.DataFrame.from_dict(dictionary)
dictionary_to_df.to_csv("test.csv",mode = "a",index = False, header = True)
You can try concating all the dataframes generating from the loop to one bigger dataframe您可以尝试将从循环生成的所有数据帧连接到一个更大的数据帧
dfs = []
for loop
dictionary = {"key1":[],"key2":[],"key3":[]}
dictionary["key1"].append(parse_value1)
dictionary["key2"].append(parse_value2)
dictionary_to_df = pd.DataFrame(dictionary)
dfs.append(dictionary_to_df)
df = pd.concat([dfs])
df.to_csv("csv path", mode = "a",index = False, header = True)
Or make the dictionary
is global for the for-loop
或者使
dictionary
对于for-loop
是全局的
dictionary = {"key1":[],"key2":[],"key3":[]}
for loop
dictionary["key1"].append(parse_value1)
dictionary["key2"].append(parse_value2)
dictionary_to_df = pd.DataFrame(dictionary)
dictionary_to_df.to_csv("csv path", mode = "a",index = False, header = True)
Or check the file header existence或者检查文件头是否存在
for loop
dictionary = {"key1":[],"key2":[],"key3":[]}
dictionary["key1"].append(parse_value1)
dictionary["key2"].append(parse_value2)
dictionary_to_df = pd.DataFrame(dictionary)
with open("csv path", 'a') as f:
dictionary_to_df.to_csv(f,mode = "a",index=False, header=not f.tell())
I solved the issue by我解决了这个问题
output.csv
fileoutput.csv
文件output.csv
file with header option = false
header option = false
将数据框附加到output.csv
文件中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.