【问题标题】:Writing Multiple Rows to CSV using Numpy Arrays without Brackets?使用不带括号的 Numpy 数组将多行写入 CSV?
【发布时间】:2016-03-07 18:11:12
【问题描述】:

我正在准备将一些数据放入 R 中。这些数据来自 Python,被导出为 CSV 文件。 R 正在读取数据,因为它只有两列,因为 numpy 数组被导出到 CSV 中,括号括起来,如下所示:

loudness_momentary,"[-83.84079859 -83.67103055 -83.80533271]"

我认为问题正在产生,因为当我将数据写入 CSV 时,会出现一个“列表中的列表”,如下所示:

data = [ 
    ['loudness_momentary', loudness_momentary],
    ['loudness_short', loudness_short],
    ['loudness_integrated', loudness_integrated],
    ['lra', lra],
    ['crest_factor_1s', crest_factor_1s],
    ['crest_factor_100ms', crest_factor_100ms],
    ['spectral_centroid', spectral_centroid],
    ['spectral_spread', spectral_spread],
    ['spectral_skewness', spectral_skewness],
    ['spectral_kurtosis', spectral_kurtosis],
    ['zcr', zcr],
    ['spectral_rolloff', spectral_rolloff],
    ['spectral_crest_factor', spectral_crest_factor],
    ['spectral_flatness', spectral_flatness],
    ['spectral_flux', spectral_flux]
    ]

    # Write to CSV File
    with open(filepath + "/" + file_name + ".csv", "wb") as stem_data:
        w = csv.writer(stem_data, delimiter=',')
        print "Writing %s to csv" % file_name
        w.writerows(data)
    stem_data.close()

我的目标是给每一行一个“标题”,让我知道数据是什么。如果我去掉“列表中的列表”问题,只写一行,数据正常写入。

所以基本上,我正在尝试为每一行输出一个带有“字符串”标题的 CSV 文件,之后的每一行都是一个 numpy 数组,没有括号或引号包围它,所以我可以很好地将它放入 R 中。

任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: python r csv numpy


    【解决方案1】:

    data 转换为列表列表:

    data = [[row[0]]+row[1].tolist() for row in data]
    

    例如,如果data 开头类似

    In [34]: data = [['foo', np.array([1,2,3])], ['bar', np.array([1,2,3])]]
    

    然后

    In [35]: data = [[row[0]]+row[1].tolist() for row in data]
    

    data 转换为这个列表列表:

    In [36]: data
    Out[36]: [['foo', 1, 2, 3], ['bar', 1, 2, 3]]
    

    顺便说一句,您最好使用with-statement 打开文件。但是请注意,当执行流程离开with-block 时,Python 会自动关闭文件。所以在离开with-block 之后显式调用stem_data.close() 是不必要的。

    【讨论】:

    • 对不起,我的错误。 row[1:] 返回一个包含 NumPy 数组的列表。我应该改用row[1]
    猜你喜欢
    • 2015-08-07
    • 2018-03-23
    • 2016-09-27
    • 1970-01-01
    • 2017-01-30
    • 2019-02-23
    • 2019-09-22
    • 2019-08-11
    • 2019-04-09
    相关资源
    最近更新 更多