简体   繁体   English

将多个numpy数组写入文件

[英]Write multiple numpy arrays to file

I know how to use numpy.savetxt to write an array to a file. 我知道如何使用numpy.savetxt将数组写入文件。 How can I write multiple arrays to the same file? 如何将多个数组写入同一个文件?

Essentially I want to do math to a column of numbers, and then replace the old column with the modified numbers. 基本上我想对一列数字进行数学运算,然后用修改后的数字替换旧列。 I read the easiest way to do this is to write a new file completely, put the modified numbers in, and just 'copy and paste' the other numbers in the file. 我读到最简单的方法是完全编写一个新文件,将修改后的数字放入,然后“复制并粘贴”文件中的其他数字。

Any help is appreciated. 任何帮助表示赞赏。

Thanks! 谢谢!

Answering a very old post for my own use. 回答一个非常古老的帖子供我自己使用。 I've used the following to write out two 1D arrays of same size as CSV. 我用以下内容写出了两个与CSV大小相同的1D阵列。

import numpy as np

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
# >>> [(1, 4), (2, 5), (3, 6)]

# Save the array back to the file
np.savetxt('z.csv', zipped, fmt='%i,%i')

If you're wanting to write multiple arrays to a file for later use, Look into numpy.savez . 如果您想将多个数组写入文件供以后使用,请查看numpy.savez

However, from your description, it sounds like you're wanting to do something with a particular column of a delimited text file. 但是,根据您的描述,听起来您想要对分隔文本文件的特定列执行某些操作。

In that case, just load the entire thing in and operate on just the column you need to. 在这种情况下,只需加载整个内容并仅操作您需要的列。

Eg 例如

import numpy as np

data = np.loadtxt('test.txt')

# Multiply the 4th column by 5
data[:,3] *= 5

# Do something more complicated to the 2nd column
data[:,1] = np.cos(data[:,1])

# Save the array back to the file
np.savetxt('test.txt', data)
import numpy


list1 = [1, 2, 3, 4]

list2 = [0.45, 0.98, 0.89, 0.21]

dat = numpy.array([list1, list2])

dat = dat.T

numpy.savetxt('data.txt', dat, delimiter = ',')

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

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