2024-09-28 22:25:06 发布
网友
我想创建如下CSV文件:
Features, Value f1, 1 f2, 2 f3, 3
但我明白了:
f1, f2, f3 1, 2, 3
我写的代码是:
my_dict = {'f1': 1, 'f2': 2, 'f3': 3} with open('testcsv.csv', 'w') as f: w = csv.DictWriter(f, my_dict.keys()) w.writeheader() w.writerow(my_dict)
我该怎么办
熊猫在这里有点过分,csv模块就足够了。只是你用错了方法:
with open('testcsv.csv', 'w', newline='') as f: w = csv.writer(f) w.writerow(['Features', 'Value']) # first write a header line for f, v in my_dict.items(): w.writerow((f,v)) # then one row per item in the dict
您需要首先根据预期的结构转换数据
data = [{'Features':i,'Value':my_dict[i]} for i in my_dict]
一旦您这样做,您可以使用pandas将其保存为CSV,如下所示:
import pandas as pd df = pd.DataFrame(data) df.to_csv('testcsv.csv',index=None)
生成的csv:
Features,Value f1,1 f2,2 f3,3
熊猫在这里有点过分,csv模块就足够了。只是你用错了方法:
您需要首先根据预期的结构转换数据
一旦您这样做,您可以使用pandas将其保存为CSV,如下所示:
生成的csv:
相关问题 更多 >
编程相关推荐