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

2024-04-20 02:47:47 发布

您现在位置: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()

Tags: 数据infromimportfftfordatalen
3条回答

你可以使用csv.writer文件()要完成此任务,请参阅:https://docs.python.org/2.6/library/csv.html

基本用法:

将列表压缩成行:

rows=zip(powery,powerx)

使用csv写入程序将数据写入csv文件:

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

根据您想要使用该文件的目的,我建议使用^{}模块或^{}模块。你知道吗

以CSV数据的形式编写文件将使您能够用电子表格打开它,绘制它的图形,编辑它,等等

以JSON数据的形式编写文件将使您能够快速地将其导入到其他编程语言中,并对其进行检查(通常是只读的,如果您想进行认真的编辑,请使用CSV)。你知道吗

这就是如何将两个不同列表中的数据写入两列中的文本文件。你知道吗

# 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(index[i])+"\t")

WITH

fwm.write(str(index[i])+",")

相关问题 更多 >