我有一个文本文件,其中的值如下:
1913 - 5,588,048
1914 - 4,202,179
1915 - 1,172,258
1916 - 2,481,675
1917 - 5,521,373
1918 - 6,052,289
1919 - 7,835,400
1920 - 1929
1920 - 10,649,851
1921 - 2,582,495
1922 - 4,763,186
我想要这两列数字的二维图。 19xx和x轴,y轴上的另一列。我在使用split()摆脱' - '并删除''出于某种原因出现。
到目前为止我的代码:
import numpy as np
import matplotlib.pyplot as plt
with open("Nickels.txt") as f:
data = f.read()
data = data.split('\n')
data2 = [row.split(' - ',1) for row in data] # to get rid of ' - '
data2[:] = [item for item in x if item != ''] # to get rid of ''
x = []
y = []
for i in range(len(x)): #making lists
x.append(0)
y.append(0)
for j in enumerate(data2):
x[i] = data2[:1]
print(x1)
#will proceed after part above works.
#fig = plt.figure()
#ax1.plot(x1,y1, c='r', label='Data')
#plt.show()
答案 0 :(得分:1)
此代码可以解决您的问题:
将numpy导入为np 将matplotlib.pyplot导入为plt
x = []
y = []
with open('Nickels.txt') as file:
for line in file:
d1 = line.strip().split('-') # Splits X and Y constituents
if len(d1) !=2: continue # Skips the empty lines
d2 = d1[1].strip().split(',') # Splits Y columns
if len(d2) !=3: continue # Skips range lines
x.append(int(d1[0].strip())) # Builds X
y.append(int(''.join(d2))) # Builds Y
x的内容:
[1913, 1914, 1915, 1916, 1917, 1918, 1919, 1920, 1921, 1922]
y的内容:
[5588048,
4202179,
1172258,
2481675,
5521373,
6052289,
7835400,
10649851,
2582495,
4763186]