代码之家  ›  专栏  ›  技术社区  ›  Axle Max

将python列表转换为np.数组. 进程正在删除sting类型的数据

  •  0
  • Axle Max  · 技术社区  · 7 年前

    我的目标是将这个字符串列表转换为Numpy数组。

    我要将前2列转换为数值数据(整数)

    list1 = [['380850', '625105', 'Dota 2'],
          ['354804', '846193', "PLAYERUNKNOWN'S BATTLEGROUNDS"],
          ['204354', '467109', 'Counter-Strike: Global Offensive']
         ]
    
    dt = np.dtype('i,i,U')
    cast_array = np.array([tuple(row) for row in sl], dtype=dt)
    print(cast_array)
    

    [OUT] [(380850, 625105, '') (354804, 846193, '') (204354, 467109, '')]
    

    我正在丢失字符串数据。我对

    1. 在numpy数组中查找将前2列转换为integer类型的任何解决方案

    This answer 给了我一个方法,但似乎不适合弦乐

    3 回复  |  直到 7 年前
        1
  •  0
  •   Axle Max    7 年前

    感谢用户:9769953的评论,这是解决方案。

    #when specifying strings you need to specify the length (derived from longest string in the list)
    dtypestr = 'int, int, U' + str(max([len(i[2]) for i in plist1]))
    
    cast_array = np.array([tuple(row) for row in plist1], dtype=dtypestr)
    
    print(np.array(cast_array))
    
        2
  •  0
  •   B. M.    7 年前

    最简单的方法是在高层使用熊猫,就像在评论中所说的那样,它将无声地处理棘手的问题:

    In [64]: df=pd.DataFrame(list1)
    
    In [65]: df2=df.apply(pd.to_numeric,errors='ignore')
    
    In [66]: df2
    Out[66]: 
            0       1                                 2
    0  380850  625105                            Dota 2
    1  354804  846193     PLAYERUNKNOWN'S BATTLEGROUNDS
    2  204354  467109  Counter-Strike: Global Offensive
    
    In [67]: df2.dtypes
    Out[67]: 
    0     int64
    1     int64
    2    object
    dtype: object
    

    df2.iloc[:,:2].values

        3
  •  0
  •   Eric    7 年前

    您的数据类型不是您所期望的-您正在遇到 https://github.com/numpy/numpy/issues/8969 :

    >>> dt = np.dtype('i,i,U')
    >>> dt
    dtype([('f0', '<i4'), ('f1', '<i4'), ('f2', '<U')])
    >>> dt['f2'].itemsize
    0  # 0-length strings!
    

    >>> dt = np.dtype('i,i,16U')
    

    或者使用 object 存储可变长度字符串的类型:

    >>> dt = np.dtype('i,i,O')