[英]Saving arrays of float in a .txt file in columns
I have 15 arrays of float (130 x 150) each, called (a,b,c,d,..,q).我每个都有 15 个 arrays 的浮点数 (130 x 150),称为 (a,b,c,d,..,q)。 And I would like to save these to a.txt file called array.txt.
我想将这些保存到名为 array.txt 的.txt 文件中。 The format should be 15 columns for 19500 rows, where array a occupy the entire first column, b the second etc.. The elements from each array should be picked rows by rows.
格式应为 19500 行的 15 列,其中数组 a 占据整个第一列,b 占据第二列,依此类推。每个数组中的元素应逐行选取。
Can someone help me with this?有人可以帮我弄这个吗? How can I do it?
我该怎么做? I was thinking with 15 for loops for each element of the arrays, but I think that is not smart and better methods are possible.
我正在考虑为 arrays 的每个元素使用 15 个 for 循环,但我认为这并不聪明,可能有更好的方法。
Thanks.谢谢。
import numpy as np
import pandas as pd
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = [11,12,13,14,15]
l = zip(a,b,c)
df = pd.DataFrame(l, columns=["a","b","c"])
np.savetxt(r'array.txt', df.values, fmt='%f')
This will combine the lists "a","b" and "c" and write them to a text file named array.txt这将组合列表“a”、“b”和“c”并将它们写入名为 array.txt 的文本文件
I too would normally recommend using Pandas for these operations, but if you are required to use Numpy, you could try something like this:我通常也会推荐使用 Pandas 进行这些操作,但如果您需要使用 Numpy,您可以尝试这样的操作:
import numpy as np
import pandas as pd
# Set up dummy-problem
data = {key: np.random.random((130, 150)) for key in "ABCDEFGHIJKLMNOPQ"}
# You would probably create a list containing the variables [a, b, c, ..., q]
# Concatenate results and save data
result = np.concatenate([a.flatten("F")[:, None] for a in data.values()], axis=1)
np.savetxt("data.txt", result)
# PS! To read as a Pandas DataFrame, use
pd.DataFrame({key: a.flatten("F") for key, a in data.items()})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.