I have 15 arrays of float (130 x 150) each, called (a,b,c,d,..,q). And I would like to save these to a .txt file called array.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.
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.
Thanks.
CodePudding user response:
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
CodePudding user response:
I too would normally recommend using Pandas for these operations, but if you are required to use Numpy, you could try something like this:
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()})