在 argparse 中使用 numpy 数据类型

Using numpy data types in argparse

我正在设置一个 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对此也没有问题。

Common built-in types and functions can be used directly as the value of the type argument

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

感谢您的帮助!

使用

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

inputtype = inputdata[c].dtype.type

.type 属性是可调用的,可用于创建该数据类型的新实例。