【问题标题】:Trying to simplify reading in csv and array initialization into numpy arrays试图简化读取 csv 和数组初始化为 numpy 数组
【发布时间】:2014-01-07 16:26:08
【问题描述】:

我是使用 Numpy 的新手。我正在尝试简化阅读功能并设置初始化我的 numpy 数组。

我希望 feature_name 包含第 0-4 列的所有特征,_X 包含所有行和第 0 - 4 列,_y 包含第 5 列的所有行。

我的代码有效,但它不像我希望的那样简洁或易于理解

import csv 
import numpy as np

# read in the data as rows 
with open('data.csv', 'rb') as csvfile: 
    _reader = csv.reader( csvfile, delimiter =',',quotechar ='"') 

    # Read in the feature names into an array
    feature_names = _reader.next() 

    # Read the in the sample data
    _X, _y = [], []
    for row in _reader: 
        _X.append( row ) #read in plant  
        _y.append( row[ 5]) 

feature_names = np.array(feature_names) 
_X      = np.array( _X) 
_y      = np.array( _y)

_X = _X[:, [0,1,2,3,4]] 
_names = feature_names[[ 0,1,2,3,4]]

非常感谢您的帮助,并希望改进我的编码!提前致谢

【问题讨论】:

    标签: python arrays csv numpy


    【解决方案1】:

    在我看来,您正在重新实现 Pandas 包。具体来说, pandas.read_csv(), 和pandas.DataFrame。见10 minutes of pandas

    您也可以使用numpy.genfromtxt()

    【讨论】:

    • 感谢 cyborg,我需要将东西放入 numpy 数组作为随机森林的参数,我从未使用过 pandas,并且可能无法使用它。我感谢任何进一步的建议
    • 我尝试使用它,但它不再是浮点数组 ....(12.0, 0.0, 0.0, 1.0, 0.0, 1.0), (18.0, 1.0, 0.0, 1.0, 0.0 , 0.0), (31.194181, 0.0, 0.0, 0.0, 1.0, 0.0)], dtype=[('Number_of_spines', '
    猜你喜欢
    • 2018-12-04
    • 2011-05-30
    • 2015-12-25
    • 2014-06-28
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    相关资源
    最近更新 更多