简体   繁体   English

字典numpy arrays到(转)csv

[英]Dictionary of numpy arrays to (transposed) csv

I've a dictionary of numpy float arrays:我有一本 numpy 浮点数 arrays 的字典:

labels = 'L0', 'L1', 'L2'
x = {'a': array([1.0, 1.1, 1.2]), 'b':array([2.0, 2.1, 2.2])}

I'd like to get a.csv file something like我想得到一个.csv 文件之类的

'Label','a', 'b'
'L1',1.0, 2.0
'L2',1.1, 2.1
'L3',1.2, 2.2

New to Python... I'm somewhat lost... Thx. Python 的新手...我有点迷路...谢谢。 for your help!您的帮助!

Pandas has exactly the thing. Pandas就是这样。 You will love it你会喜欢的

import pandas as pd

dataframe = pd.DataFrame(x, index=labels)
dataframe.to_csv('filename.csv')

You can use pythons csv-module for that.您可以为此使用 pythons csv-module You would need to specify quotechar="'" and quoting=csv.QUOTE_NONNUMERIC to ensure the quoting you wanted:您需要指定quotechar="'"quoting=csv.QUOTE_NONNUMERIC以确保您想要的引用:

import numpy as np

labels = 'L0', 'L1', 'L2'
x = {'a': np.array([1.0, 1.1, 1.2]), 'b':np.array([2.0, 2.1, 2.2])}

import csv

with open("d.txt","w", newline="") as f:
    # ensure quoting of non numerics
    wr = csv.writer(f, quotechar="'", quoting=csv.QUOTE_NONNUMERIC)
    header = ["Label"] + [k for k in x.keys()]
    wr.writerow(header)
    data = zip(labels,*x.values())
    for d in data:
        wr.writerow(d)

print(open("d.txt").read())

Output of file: Output 文件:

'Label','a','b'
'L0',1.0,2.0
'L1',1.1,2.1
'L2',1.2,2.2

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

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