如何通过numpy loadtext获取标签?
问题描述:
Col0 Col1 Col2
2015 1 4
2016 2 3
形式的数据是浮点数据文件,我用numpty
loadtext
做出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)
注:标签(列标题)是在脚本未知。该脚本应该是通用的,以便与任何具有相同结构的输入文件一起工作。
答
使用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()
答
这是不是一个真正的答案,实际的问题,但我觉得你可能有兴趣知道如何做熊猫,而不是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()
会导致
可以看出,没有必要知道任何列名和剧情被自动标记。
当然然后也可以使用的数据与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()
通常人们使用大熊猫这样的任务。 'df = pandas.read_csv()'会给你一个带有命名列的数据框,这样你就可以在'df.columns'中访问列名。 – ImportanceOfBeingErnest