Efficient way to convert delimiter separated string to numpy array

前端 未结 3 1824
独厮守ぢ
独厮守ぢ 2020-12-31 05:29

I have a String as follows :

1|234|4456|789

I have to convert it into numpy array.I would like to know the most efficient way.Since I will

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 05:55

    Try this:

    import numpy as np
    s = '1|234|4456|789'
    array = np.array([int(x) for x in s.split('|')])
    

    ... Assuming that the numbers are all ints. if not, replace int with float in the above snippet of code.

    EDIT 1:

    Alternatively, you can do this, it will only create one intermediate list (the one generated by split()):

    array = np.array(s.split('|'), dtype=int)
    

    EDIT 2:

    And yet another way, possibly faster (thanks for all the comments, guys!):

    array = np.fromiter(s.split("|"), dtype=int)
    

提交回复
热议问题