automatic detection/conversion of data types?

前端 未结 1 1389
陌清茗
陌清茗 2021-01-03 09:37

Is there a function in numpy that determines whether strings should be integers or floating point numbers and automatically converts them? For instance, I often have a colle

相关标签:
1条回答
  • 2021-01-03 10:03

    numpy.genfromtxt can guess dtypes if you set dtype=None:

    import numpy as np
    import io
    
    alist = [['1','a','.3'],
            ['2','b','-.5']]
    
    f = io.BytesIO('\n'.join(' '.join(row) for row in alist))
    arr = np.genfromtxt(f,dtype=None)
    print(arr)
    print(arr.dtype)
    # [(1, 'a', 0.3) (2, 'b', -0.5)]
    # [('f0', '<i4'), ('f1', '|S1'), ('f2', '<f8')]
    

    Note that it would be better to apply np.genfromtxt directly to your text file instead of creating the intermediate list List (or what I called alist). If you need to do some processing of the file before sending it to np.genfromtxt, you could make a file-like object wrapper around the file which can do the processing and be passed to np.genfromtxt.

    0 讨论(0)
提交回复
热议问题