【问题标题】:Is it possible to change the type of just one column in a numpy array created from genfromtxt?是否可以更改从 genfromtxt 创建的 numpy 数组中仅一列的类型?
【发布时间】:2014-05-10 23:16:06
【问题描述】:

我正在创建一个 numpy 数组,然后将其导出到 django 模型中。作为 dtype 属性,我有一个 None,但我有一列应该是一个允许 NULL 值的整数。现在,当在 csv 中找到一个 'NULL' 字符串时,该列的类型在 bool 中发生了变化,它不允许 None。

现在,是否有可能只为该列执行dtype={'name of the columns', 'int'} 之类的操作,并让其余列仍然为 None 并让 numpy 决定类型?

【问题讨论】:

    标签: python django numpy types genfromtxt


    【解决方案1】:

    假设你说的是 genfromtxt,你可以使用 dtype 参数设置 dtype:

    例如

    如果您的文件包含

    1.0 2.0 3.0 4.0
    1.0 2.0 3.0 4.0
    1.0 2.0 3.0 4.0
    1.0 2.0 3.0 hello
    

    然后

    a=np.genfromtxt('vlen.txt',dtype=[('col0', 'i4'), ('col1', '<f8'), ('col2', '<f8'), ('col3', 'S5')])
    
    a['col0']
    array([1, 1, 1, 1]) # note ints not floats
    

    【讨论】:

    • 我想知道是否必须为每一列编写一个元组,或者我是否可以只定义一个,而将其他的留给 numpy。最后我用熊猫解决了。
    猜你喜欢
    • 2016-08-14
    • 2013-01-19
    • 2019-07-27
    • 2012-05-29
    • 1970-01-01
    • 2012-08-07
    • 2012-12-14
    • 2019-04-16
    • 2020-03-31
    相关资源
    最近更新 更多