【问题标题】:Using numpy data types in argparse在 argparse 中使用 numpy 数据类型
【发布时间】:2016-11-01 10:54:14
【问题描述】:

我正在设置一个 Argparse 解析器来通过 shell 读取一些用户输入。输入将用于从包含字符串和数字的 pandas DataFrame 中提取数据。我想在 Argparse.add_argument() 中自动设置 type= 参数以匹配相应列的数据类型。

我的想法是像这样设置 Argparse 参数,其中 inputdata 是 DataFrame:

for c in inputdata.columns:
        inputname= c
        inputtype= np.dtype(inputdata[c])
        parser.add_argument("--"+inputname, type=inputtype)

但是,这不起作用:Python 引发了 ValueError: dtype('int64') is not callable 。我认为这是因为我没有正确输入 Numpy 文件类型;如果我例如将 inputtype 设置为 float,一切按计划进行。如果我手动输入type=np.int64,Argparse 也没有这个问题。

  • 如何让它接受我的 DataFrame 中的文件类型,即上面显示的循环中的 int64object?我也尝试了一些选项here,例如dtype.type 但没有任何效果。

  • 或者这是不可能的? Argparse docs 仅声明

常见的内置类型和函数可以直接用作类型参数的值

但正如我上面所说,如果明确输入,numpy 数据类型似乎很好。

感谢您的帮助!

【问题讨论】:

  • 在这种情况下,callable 通常是一个函数,它接受一个字符串(来自您的输入)并将其转换为其他内容。并引发错误是输入字符串格式错误。 np.int64('123') 有效。 np.dtype('int64')('123') 没有。

标签: python numpy pandas user-input argparse


【解决方案1】:

使用

inputtype = np.dtype(inputdata[c]).type

inputtype = inputdata[c].dtype.type

.type 属性是可调用的,可用于创建该 dtype 的新实例。

【讨论】:

    猜你喜欢
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多