use*_*440 32 python scikit-learn
根据我的理解,scikit-learn接受(n-sample,n-feature)格式的数据,这是一个2D数组.假设我有表格中的数据......
Stock prices indicator1 indicator2
2.0 123 1252
1.0 .. ..
.. . .
.
Run Code Online (Sandbox Code Playgroud)
我该如何导入?
den*_*son 60
来自Pandas的read_csv是numpy loadtxt的一个非常好的替代品.数据被加载到Pandas数据框中,其最大优点是可以处理混合数据类型,例如某些列包含文本,其他列包含数字.然后,您可以轻松地仅选择数字列并使用as_matrix转换为numpy数组.Pandas还会读/写excel文件和一堆其他格式.
如果我们有一个名为"mydata.csv"的csv文件:
point_latitude,point_longitude,line,construction,point_granularity
30.102261, -81.711777, Residential, Masonry, 1
30.063936, -81.707664, Residential, Masonry, 3
30.089579, -81.700455, Residential, Wood , 1
30.063236, -81.707703, Residential, Wood , 3
30.060614, -81.702675, Residential, Wood , 1
Run Code Online (Sandbox Code Playgroud)
这将读入csv并将数字列转换为scikit_learn的numpy数组,然后修改列的顺序并将其写入excel电子表格:
import numpy as np
import pandas as pd
input_file = "mydata.csv"
# comma delimited is the default
df = pd.read_csv(input_file, header = 0)
# for space delimited use:
# df = pd.read_csv(input_file, header = 0, delimiter = " ")
# for tab delimited use:
# df = pd.read_csv(input_file, header = 0, delimiter = "\t")
# put the original column names in a python list
original_headers = list(df.columns.values)
# remove the non-numeric columns
df = df._get_numeric_data()
# put the numeric column names in a python list
numeric_headers = list(df.columns.values)
# create a numpy array with the numeric values for input into scikit-learn
numpy_array = df.as_matrix()
# reverse the order of the columns
numeric_headers.reverse()
reverse_df = df[numeric_headers]
# write the reverse_df to an excel spreadsheet
reverse_df.to_excel('path_to_file.xls')
Run Code Online (Sandbox Code Playgroud)
Fre*_*Foo 51
这不是CSV文件; 这只是一个空格分隔的文件.假设有没有缺失值,你可以很容易地这样加载到一个数组numpy的所谓data与
import numpy as np
f = open("filename.txt")
f.readline() # skip the header
data = np.loadtxt(f)
Run Code Online (Sandbox Code Playgroud)
如果股票价格是您想要预测的(您的y价值,以scikit-learn术语表示),那么您应该data使用
X = data[:, 1:] # select columns 1 through end
y = data[:, 0] # select column 0, the stock price
Run Code Online (Sandbox Code Playgroud)
或者,您可以按摩标准Python csv模块来处理这种类型的文件.
小智 19
您可以在numpy中查找loadtxt函数.
将可选输入添加到loadtxt方法中.
对csv的一个简单改变是
data = np.loadtxt(fname = f, delimiter = ',')
Run Code Online (Sandbox Code Playgroud)