我需要在一个包含两行的文件中绘制一个折线图:一行为APPL股票,一行为NFLX股票。 x轴是时间。我无法弄清楚如何指出y是文件中的数字。
文本: 120.96,120.95,120.72,120.77,120.92,121.1,121.26,121.63,121.68,121.56,121.59,121.5,121.52,121.4,121.33,121.31,121.47,121.58,121.785,121.76,121.55,121.4308,121.47,121.45,121.4699, 121.53,121.5,121.6399,121.6,121.525,121.29,121.28,121.125,121.18,121.28,121.145,121.16,121.11,121.26,121.43,121.4,121.289,121.32,121.39,121.2898,121.33,121.28,121.46,121.32,121.35 121.26,121.07,121.09,121.083,121.08,.....
113.36,113.21,113.3,113.33,113.56,113.805,113.81,113.76,113.75,113.896,113.75,113.43,113.44,113.29,113.253,113.17,113.39,113.36,113.65,113.9,113.65,113.51,113.51,113.5 ,113.3,113.39,113.278,113.105,113.011,113.0,112.839,112.879,112.85,113.026,112.915,112.878,112.88,112.74,112.91,112.78,112.775,112.725,112.69,112.62,112.61,112.73,112.6,112.79,112.746 ,112.77,112.66,112.46,112.54,112.585,....import matplotlib.pyplot as plt
import numpy as np
f = open('AAPL-NFLX.txt', 'r')
stock_list = f.read().split(',')
line_1 = stock_list[:391]
line_2 = stock_list[391:]
x = np.linspace(0, 391)
y = line_1[0::2]
z = line_2[0::2]
plt.plot(x, y, 'y--', label='APPL')
plt.plot(x, z, 'r-', label='NFLX')
plt.legend(loc = 'lower right')
plt.xlabel("Time in Minutes")
plt.ylabel("Stock Price")
答案 0 :(得分:0)
以下是我如何将文件的第一列读入列表。
with open('AAPL-NFLX.txt', 'r') as f:
stock_list = [line.split(',')[0] for line in f.readline()]
你打开一个文件(with
语句来表示confort和readability),然后遍历这些行(对f.readline()进行列表理解)并从文件中删除第一个元素。
重要的一点是:如果您拥有CSV文件(逗号分隔值),而不仅仅是带有逗号的无格式文本,请使用专用的python csv module:
with open('AAPL-NFLX.txt', 'r') as f:
reader = csv.reader(f)
stock_list = [line[0] for line in reader]
这样可以更容易阅读和维护(例如将换行符分隔符更改为;
,跳过行,读取字典...)
对于像在光速下将CSV读入Numpy数组这样的奇特事物,你可以使用惊人的(如果复杂的)numpy.loadtxt。像地狱一样优化。
numpy.loadtxt(fname,dtype =,comments ='#',delimiter = None,converter = None,skiprows = 0,usecols = None,unpack = False,ndmin = 0)[来源] ]
您的代码变为
stock_list = numpy.loadtxt('AAPL-NFLX.txt',dtype=float,usecols=1)
动臂。心灵震撼。