将 OrderedDict 对象保存到 csv 文件

Save an OrderedDict Object to a csv file

我有以下对象,它是一个我想导出到 csv 的 OrderedDict。

OrderedDict([('AGG', 0.09888),
             ('BWX', 0.04886),
             ('DBC', 0.06046),
             ('EMB', 0.05899),
             ('HYG', 0.07954),
             ('IEF', 0.09933),
             ('LQD', 0.07909),
             ('MBB', 0.10442),
             ('MUB', 0.09408),
             ('PCY', 0.05172),
             ('RING', 0.0026),
             ('SHM', 0.03761),
             ('SHY', 0.11148),
             ('SPY', 0.07296)])

我正在使用 .to_csv 命令,但错误消息显示:“'collections.OrderedDict' 对象没有属性 'to_csv'”

是否需要将其转换为 df 或 np 数组?

谢谢

您可以手动编写 CSV 文件:

with open('output.csv', 'w') as f:
    for key,val in odict.items():
        f.write('{},{}\n'.format(key, val))

改用pandas

d = OrderedDict([('AGG', 0.09888),
             ('BWX', 0.04886),
             ('DBC', 0.06046),
             ('EMB', 0.05899),
             ('HYG', 0.07954),
             ('IEF', 0.09933),
             ('LQD', 0.07909),
             ('MBB', 0.10442),
             ('MUB', 0.09408),
             ('PCY', 0.05172),
             ('RING', 0.0026),
             ('SHM', 0.03761),
             ('SHY', 0.11148),
             ('SPY', 0.07296)])
pd.DataFrame.from_dict(d, orient="index").to_csv("data.csv")

解决方案

我的第一选择是使用 pandas,因为从用户实现的角度来看它很简单。

import pandas as pd
pd.DataFrame(d.items()).to_csv('test.csv', index=False)

替代解决方案

但是,如果出于某种原因您不想使用 pandas,那么您可以使用以下实现.

Note: I am using the OrderedDict (d) from the Dummy Data section below.

创建 CSV 文件:test.csv

# Create lines
CSV_FILENAME = 'test.csv'
lines = [','.join(list(map(str,items))) for items in d.items()]
# Create csv file
with open(CSV_FILENAME, 'w') as f:
    f.write('\n'.join(lines))

检查 test.csv

中的文件输出
# Check if csv file was properly created    
with open(CSV_FILENAME, 'r') as f:
    s = f.read()

print(s)

输出

# test.csv

AGG,0.09888
BWX,0.04886
DBC,0.06046
EMB,0.05899
HYG,0.07954
IEF,0.09933
LQD,0.07909
MBB,0.10442
MUB,0.09408
PCY,0.05172
RING,0.0026
SHM,0.03761
SHY,0.11148
SPY,0.07296

虚拟数据

from collections import OrderedDict

d = OrderedDict([('AGG', 0.09888),
             ('BWX', 0.04886),
             ('DBC', 0.06046),
             ('EMB', 0.05899),
             ('HYG', 0.07954),
             ('IEF', 0.09933),
             ('LQD', 0.07909),
             ('MBB', 0.10442),
             ('MUB', 0.09408),
             ('PCY', 0.05172),
             ('RING', 0.0026),
             ('SHM', 0.03761),
             ('SHY', 0.11148),
             ('SPY', 0.07296)])