【问题标题】:How to import csv data file into scikit-learn?如何将 csv 数据文件导入 scikit-learn?
【发布时间】:2012-06-16 21:56:44
【问题描述】:

据我了解,scikit-learn 接受 (n-sample, n-feature) 格式的数据,这是一个 2D 数组。假设我有表单中的数据...

Stock prices    indicator1    indicator2
2.0             123           1252
1.0             ..            ..
..              .             . 
.

如何导入?

【问题讨论】:

    标签: python scikit-learn


    【解决方案1】:

    numpy loadtxt 的一个很好的替代品是read_csv from Pandas。数据被加载到 Pandas 数据帧中的一大优势是它可以处理混合数据类型,例如某些列包含文本,而其他列包含数字。然后,您可以轻松地仅选择数字列并使用as_matrix 转换为 numpy 数组。熊猫也会read/write excel files and a bunch of other formats

    如果我们有一个名为“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
    

    这将读入 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')
    

    【讨论】:

    • 好的,但是如何从该矩阵创建一个 scikit learn 数据集?
    • Scikit learn 可以将 pandas 数据帧作为输入,所以它几乎准备好了。假设“point_granularity”是您可以执行的目标变量 y = df['point_granularity'] 和 X = df[['point_latitude'',point_longitude','line,construction']]
    • 由于某些特征是分类的,您需要对大多数 scikit-learn 模型进行一次热编码:stackoverflow.com/a/43038709/1810559
    【解决方案2】:

    这不是 CSV 文件;这只是一个空格分隔的文件。假设没有缺失值,您可以轻松地将其加载到名为 data 的 Numpy 数组中

    import numpy as np
    
    f = open("filename.txt")
    f.readline()  # skip the header
    data = np.loadtxt(f)
    

    如果股票价格是您想要预测的(您的 y 值,在 scikit-learn 术语中),那么您应该使用拆分 data

    X = data[:, 1:]  # select columns 1 through end
    y = data[:, 0]   # select column 0, the stock price
    

    或者,您也可以使用standard Python csv module 来处理此类文件。

    【讨论】:

    • 有没有办法使用这种方法来维护特征名称?
    • @AlexFZ:不直接。除了f.readline(),您还可以使用feature_names = f.readline().split() 或它的一些变体(OP 的标题行不是很好地用空格分隔)。 Pandas 有更好的功能。
    • 虽然提问者提供了一个空格分隔的文件,但问题是针对 csv 数据文件提出的。
    • 您指定的代码生成错误 ValueError: could not convert string to float:, 因为我的数据是字符串!如何解决这个问题?
    【解决方案3】:

    您可以在numpy中查找loadtxt函数。

    将可选输入获取到 loadtxt 方法中。

    对 csv 的一个简单更改是

    data =  np.loadtxt(fname = f, delimiter = ',')
    

    【讨论】:

      【解决方案4】:

      使用numpy加载csvfile

      import numpy as np
      dataset = np.loadtxt('./example.csv', delimiter=',')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-30
        • 2019-04-05
        • 2016-07-15
        • 1970-01-01
        • 2017-01-09
        • 2018-07-12
        • 2012-07-12
        • 2015-12-09
        相关资源
        最近更新 更多