Python - 将两个数据集(列表?)作为两列输出到数据文件

时间:2016-05-10 23:56:32

标签: python

对于python,我是新手。我用C ++编写了大部分的编程。我有一个程序可以生成数据集的快速傅里叶变换,并使用matplotlib在两个窗口中绘制数据和FFT。我想将数据输出到文件而不是绘图。对于C ++来说,这对我来说是一项简单的任务,但我似乎无法在python中解决这个问题。所以问题是,“如何将powerx和powery输出到两个数据集位于不同列的数据文件中?以下是程序:

import matplotlib.pyplot as plt

from fft import fft
from fft import fft_power
from numpy import array
import math
import time


# data downloaded from ftp://ftp.cmdl.noaa.gov/ccg/co2/trends/co2_mm_mlo.txt
print ' C02 Data from Mauna Loa'
data_file_name = 'co2_mm_mlo.txt'
file = open(data_file_name, 'r')
lines = file.readlines()
file.close()
print ' read', len(lines), 'lines from', data_file_name

window = False

yinput = []
xinput = []

for line in lines :
    if line[0] != '#' :
        try:
            words = line.split()
            xval = float(words[2])
            yval = float( words[4] )
            yinput.append( yval )
            xinput.append( xval )
        except ValueError :
            print 'bad data:',line


N = len(yinput)
log2N = math.log(N, 2)
if log2N - int(log2N) > 0.0 :
    print 'Padding with zeros!'
    pads = [300.0] * (pow(2, int(log2N)+1) - N)
    yinput = yinput + pads
    N = len(yinput)
    print 'Padded : '
    print len(yinput)
    # Apply a window to reduce ringing from the 2^n cutoff
    if window : 
        for iy in xrange(len(yinput)) :
            yinput[iy] = yinput[iy] * (0.5 - 0.5 * math.cos(2*math.pi*iy/float(N-1)))

y = array( yinput ) 
x = array([ float(i) for i in xrange(len(y)) ] )
Y = fft(y)

powery = fft_power(Y)
powerx = array([ float(i) for i in xrange(len(powery)) ] )

Yre = [math.sqrt(Y[i].real**2+Y[i].imag**2) for i in xrange(len(Y))]


plt.subplot(2, 1, 1)
plt.plot( x, y )

ax = plt.subplot(2, 1, 2)
p1, = plt.plot( powerx, powery )
p2, = plt.plot( x, Yre )
ax.legend( [p1, p2], ["Power", "Magnitude"] )
plt.yscale('log')


plt.show()

3 个答案:

答案 0 :(得分:0)

您可以使用csv.writer()来完成此任务,这里是引用:https://docs.python.org/2.6/library/csv.html

基本用法:

压缩列表到行:

rows=zip(powery,powerx)

使用csv writer将数据写入csv文件:

with open('test.csv', 'wb') as f:
    writer = csv.writer(f)
    for row in rows:
        writer.writerow(row)

答案 1 :(得分:0)

这是您可以将两个不同列表中的数据写入两列文本文件中的方法。

# Two random lists
index = [1, 2, 3, 4, 5]
value = [4.5, 5, 7.0, 11, 15.7]

# Opening file for output
file_name = "output.txt"
fwm = open(file_name, 'w')

# Writing data in file
for i in range(len(index)):
    fwm.write(str(index[i])+"\t")
    fwm.write(str(value[i])+"\n")

# Closing file after writing
fwm.close()

如果您的列表包含字符串形式的数据,则在文件中写入数据时删除“str”。

如果要在csv文件中保存数据,请更改

  

fwm.write(STR(指数[I])+ “\ t” 的)

     

WITH

     

fwm.write(STR(指数[I])+ “”)

答案 2 :(得分:0)

根据您要使用该文件的内容,我建议使用csv模块或json模块。

将文件写为CSV数据,您可以使用电子表格打开文件,绘制图表,编辑等等。

将文件编写为JSON数据将使您能够快速将其导入其他编程语言并进行检查(通常只读 - 如果您想进行严格的编辑,请使用CSV)。

相关问题