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

我的想法是像这样设置 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 中的文件类型,即上面显示的循环中的 int64 和对象?我也尝试了一些选项 here,例如dtype.type 但没有任何效果。
  • 或者这是不可能的? Argparse docs 状态只有



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

    谢谢你的帮助!

    最佳答案


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

    或者
    inputtype = inputdata[c].dtype.type
    
    .type 属性是可调用的,可用于创建该 dtype 的新实例。

    关于python - 在 argparse 中使用 numpy 数据类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38104558/

    10-12 17:23
    查看更多