简体   繁体   English

Numpy.savetxt ----- > 如何在 python numpy 中将数组/矩阵保存到 csv?

[英]Numpy.savetxt ----- > How to save an array/matrix to a csv in python numpy?

I have created a sort of matrix/data-table in python from multiple arrays containing various kinds of data, which looks like this in the variable view:我在 python 中从包含各种数据的多个数组创建了一种矩阵/数据表,在变量视图中看起来像这样:

phones  starts  mids

sil 308000.0    308195.0

DH  308390.0    308410.0

AH0 308430.0    308445.0

B   308460.0    308525.0

These are three lists that I have combined using numpy.columnstack().这是我使用 numpy.columnstack() 组合的三个列表。 I am trying to output this table/matrix in the same format/structure but as a csv using numpy.savetxt.我正在尝试以相同的格式/结构输出此表/矩阵,但使用 numpy.savetxt 作为 csv。 Is this possible given the different variable types in each row/column?鉴于每行/列中的变量类型不同,这可能吗?

When I try to run :当我尝试运行时:

np.savetxt('blue.txt', np.column_stack((phones, phone_starts, phone_mids)), ',', fmt="%s %f")

I get the error:我收到错误:

File "<__array_function__ internals>", line 4, in savetxt
TypeError: _savetxt_dispatcher() got multiple values for argument 'fmt'

I have also tried without the 'fmt' option and have gotten a similar error.我也尝试过不使用 'fmt' 选项并遇到类似的错误。

Any ideas?有任何想法吗?

Well, do you want to save np arrays to csv with labels?那么,你想用标签将 np 数组保存到 csv 吗? that is the type of work for which pandas were created.这就是熊猫被创造出来的工作类型。

import numpy as np
import pandas as pd

data = {
"phone_starts": np.array([308000.0, 308390.0, 308430.0, 308460.0]),
"phone_mids": np.array([308195.0, 308410.0, 308445.0, 308525.0])
   }

df = pd.DataFrame(data, index=["sil", "DH", "AH0", "B"])
df.index.name = "Phone"
df.to_csv("blue.csv")

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

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