我得到了一个名为“ density_air.dat”的数据文件,我需要从每一列中提取数据并将它们放入自己的列表中(即tList将以“ -10”开头的列中包含值,而密度将包含值在以“ 1.341”开头的列中,然后需要绘制列表。我在用这些数据填充列表时遇到了麻烦...任何帮助吗?
from scitools.std import *
import sys
import pylab as pl
inFile = sys.argv[-1]
f = open(inFile, 'r')
for x in range(4):
f.readline()
tList = []
density = []
for line in f:
words = line.split()
for x in words:
tList.append(words[x])
density.append(words[x])
f.close()
plot(tList, density)
数据文件为:
# Density of air at different temperatures, at 1 atm pressure
# Column 1: temperature in Celsius degrees
# Column 2: density in kg/m^3
-10 1.341
-5 1.316
0 1.293
5 1.269
10 1.247
15 1.225
20 1.204
25 1.184
30 1.164
# Source: Wikipedia (keyword Density)
最佳答案
有一个名为numpy
的loadtxt
函数,该函数将ascii文件加载到numpy
数组中:
import numpy as np
import matplotlib.pylab as plt
import sys
inFile = sys.argv[-1]
temperature, density = np.loadtxt(inFile,unpack=True)
plt.plot(temperature, density,'ko')
plt.show()