2017-09-14 95 views
3

我在如何通过numpy loadtext获取标签?

Col0 Col1 Col2 
2015 1  4 
2016 2  3 

形式的数据是浮点数据文件,我用numptyloadtext做出ndarray。但是,我需要跳过标签行和列以获得数据数组。在阅读标签时,我怎样才能使ndarray不在数据中?

import numpy as np 
import matplotlib.pyplot as plt 

data = np.loadtxt("data.csv", skiprows=1) 
# I need to skip the first row in reading the data but still get the labels. 
x= data[:,0] 
a= data[:,1] 
b= data[:,2] 

plt.xlabel(COL0) # Reading the COL0 value from the file. 
plt.ylabel(COL1) # Reading the COL1 value from the file. 
plt.plot(x,a) 

注:标签(列标题)是在脚本未知。该脚本应该是通用的,以便与任何具有相同结构的输入文件一起工作。

+2

通常人们使用大熊猫这样的任务。 'df = pandas.read_csv()'会给你一个带有命名列的数据框,这样你就可以在'df.columns'中访问列名。 – ImportanceOfBeingErnest

回答

4

使用genfromtxt可以在元组中获取名称。您可以查询名称,并且可以使用dtype.names[n]将名称输出到变量中,其中n是索引。

import numpy as np 
import matplotlib.pyplot as plt 

data = np.genfromtxt('data.csv', names=True) 

x = data[data.dtype.names[0]] # In this case this equals data['Col1']. 
a = data[data.dtype.names[1]] 
b = data[data.dtype.names[2]] 

plt.figure() 
plt.plot(x, a) 
plt.xlabel(data.dtype.names[0]) 
plt.ylabel(data.dtype.names[1]) 
plt.show() 
+0

可能需要'delimiter =','',默认情况下只有空格。 –

+0

用这种方法,我们应该知道脚本中的列名。那么,有什么意义呢?我想从文件中读取标签。如果我在脚本中有标签,我可以跳过第一行并使用图中的标签。 – Googlebot

+1

您可以替换'Col?'命令由'data.dtype.names [?]'命令。 – Chiel

0

这是不是一个真正的答案,实际的问题,但我觉得你可能有兴趣知道如何做熊猫,而不是numpy的相同。

import pandas as pd 
import matplotlib.pyplot as plt 

df = pd.read_csv("data.csv", delim_whitespace=True) 

df.set_index(df.columns[0]).plot() 

plt.show() 

会导致

enter image description here

可以看出,没有必要知道任何列名和剧情被自动标记。

当然然后也可以使用的数据与matplotlib绘制:

import pandas as pd 
import matplotlib.pyplot as plt 

df = pd.read_csv("data.csv", delim_whitespace=True) 
x = df[df.columns[0]] 
a = df[df.columns[1]] 
b = df[df.columns[2]] 

plt.figure() 
plt.plot(x, a) 
plt.xlabel(df.columns[0]) 
plt.ylabel(df.columns[1]) 
plt.show()