【发布时间】: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
所以这只是显示问题吗?
【问题讨论】:
-
'?'是 numpy docs.scipy.org/doc/numpy/reference/arrays.dtypes.html 中的布尔类型。我不明白
标签: python arrays pandas numpy dataframe