【问题标题】:Pandas dataframe to structured array with Boolean series使用布尔系列将 Pandas 数据帧转换为结构化数组
【发布时间】:2018-12-19 10:03:07
【问题描述】:

我有一个 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')]

这是为什么?更一般地说,这是唯一的例外,还是我们每次都必须手动检查以确保已按预期处理 dtype 转换?

编辑:另一方面,似乎转换正确的:

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

所以这只是显示问题吗?

【问题讨论】:

标签: python arrays pandas numpy dataframe


【解决方案1】:

奇怪的是,NumPy 选择? 来表示布尔值。来自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)

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

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 在文档中找到此内容。

【讨论】:

    猜你喜欢
    • 2018-12-31
    • 2020-06-25
    • 2023-03-21
    • 2021-10-23
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    相关资源
    最近更新 更多