简体   繁体   中英

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). 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.

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

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()})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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