我想使用matplotlib在Python中保存和绘制某些列。列的参数将从cmdline获得,因此我将不得不使用sys.argv来获取它们。这就是我目前所拥有的:
编辑:我还应该提一下,列数可能会因用户选择的内容而异。例如,他们可以只使用列1, 2
或只列1
。
with open('./P14_data.csv', 'rb') as csvfile:
data = csv.reader(csvfile, delimiter=';')
cols = [index for index in sys.argv[1:]]
#I want to extract the columns corresponding to cols
for col in cols:
x[col] = [rows for rows in data]
print x
但是这会返回一个空列表[]。
至于输出,我想将每列绘制成一维数组。例如,使用以下形式的csv文件:
1 5
1 3
0 2
0 3
1 1
1 3
如果用户输入'1',我希望我的代码只保存数组中的第一列变量:
data = [[1, 1, 0, 0,..]]
plt.plot(data)
我知道大熊猫是一个有效的选择,但我喜欢先这样学习它。谢谢!
答案 0 :(得分:0)
您可以获取行中的第一列
with open('./P14_data.csv', 'rb') as csvfile:
data = csv.reader(csvfile, delimiter=';')
included_cols = [1,2,3]
x = [[rows[0]] for rows in data]
x1 = [[row[0].split(',')[0] for row in x]]
x2 = [[row[0].split(',')[1] for row in x]]
x3 = [[row[0].split(',')[2] for row in x]]
print x1
# [['4', '7', '3', '3']]
print x2
# [['9', '11', '5', '6']]
print x3
# [['5', '4', '2', '3']]
答案 1 :(得分:0)
这是一种将标题和数据保存在单独数组中的方法。为了得到每一列,我们采用数据数组的转置,并选择我们感兴趣的列。
这是 data.csv :
index,value1,value2
0,10,20
1,12,18
2,5,6
3,9,10
4,11,8
以下是代码:
import matplotlib.pyplot as plt
import numpy as np
import csv
with open('data.csv','r') as csvfile:
r = csv.reader(csvfile, delimiter=',')
data = [i for i in r]
headings = data.pop(0)
data = np.array([[np.float(j) for j in i] for i in data])
c1 = data.T[1]
c2 = data.T[2]
fig, ax = plt.subplots(1)
ax.plot(c1, label=headings[1])
ax.plot(c2, label=headings[2])
ax.legend()
fig.show()
答案 2 :(得分:0)
你可以试试这样的事情:
#!/usr/bin/env python3
import csv
with open('./P14_data.csv', newline='') as csvfile:
data = csv.reader(csvfile, delimiter=';')
x = [rows for rows in data]
transposed = list(zip(*x))
print(transposed)
甚至更简单:
#!/usr/bin/env python3
import csv
with open('./P14_data.csv', newline='') as csvfile:
data = csv.reader(csvfile, delimiter=';')
transposed = list(zip(*data))
print(transposed)
关键点: