2017-09-14 126 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() 
相關問題