代码之家  ›  专栏  ›  技术社区  ›  jpp

pandas数据帧到带布尔序列的结构化数组

  •  3
  • jpp  · 技术社区  · 7 年前

    我有一个pandas数据帧,希望将其转换为numpy记录数组或结构化数组。我正在使用python 3.6/pandas 0.19.2/numpy 1.11.3。

    df = pd.DataFrame(data=[[True, 1, 2],[False, 10, 20]], columns=['a','b','c'])
    
    print(df.dtypes)
    
    a     bool
    b    int64
    c    int64
    dtype: object
    

    我的尝试如下:

    # record array
    res1 = df.to_records(index=False)
    
    # structured array
    s = df.dtypes
    res2 = np.array([tuple(x) for x in df.values], dtype=list(zip(s.index, s)))
    

    然而,布尔类型在 dtype 这些结果的属性:

    print(res1.dtype)
    
    (numpy.record, [('a', '?'), ('b', '<i8'), ('c', '<i8')])
    
    print(res2.dtype)
    
    [('a', '?'), ('b', '<i8'), ('c', '<i8')]
    

    这是为什么?更一般地说,这是唯一的异常,还是每次都必须手动检查以确保数据类型转换已按预期处理?

    编辑 :另一方面,似乎是转换 对的:

    print(res1.a.dtype)     # bool
    print(res2['a'].dtype)  # bool
    

    所以这只是一个展示问题吗?

    1 回复  |  直到 7 年前
        1
  •  0
  •   jpp    7 年前

    奇怪的是,努比选择了 ? 表示布尔值。从 Data type objects (dtype) :

    '?' boolean
    'b' (signed) byte
    'B' unsigned byte
    'i' (signed) integer
    'u' unsigned integer
    'f' floating-point
    'c' complex-floating point
    'm' timedelta
    'M' datetime
    'O' (Python) objects
    'S', 'a'    zero-terminated bytes (not recommended)
    'U' Unicode string
    'V' raw data (void)
    

    令人困惑的是 Array Interface 对于从C扩展访问,使用不同的映射:

    t   Bit field (following integer gives the number of bits in the bit field).
    b   Boolean (integer type where all values are only True or False)
    i   Integer
    u   Unsigned integer
    f   Floating point
    c   Complex floating point
    m   Timedelta
    M   Datetime
    O   Object (i.e. the memory contains a pointer to PyObject)
    S   String (fixed-length sequence of char)
    U   Unicode (fixed-length sequence of Py_UNICODE)
    V   Other (void * – each item is a fixed-size chunk of memory)
    

    感谢@bobrobbob在文档中找到了这个。