【问题标题】:What is type <U12?<U12 类型是什么?
【发布时间】:2019-02-23 03:15:24
【问题描述】:

我使用pandasnumpy 处理一些数据,直到得到两个相似的数组输出:

array(['french', 'mexican', 'cajun_creole', ..., 'southern_us', 'italian',
       'thai'], dtype='<U12')

array(['french', 'mexican', 'cajun_creole', ..., 'jamaican', 'italian',
   'thai'], dtype=object)

我看不出有什么区别,&lt;U12 是什么?

【问题讨论】:

标签: python arrays pandas numpy types


【解决方案1】:

&lt;U12那是一个numpy类型:

&lt;小尾数

UUnicode

12 12 个字符:

(Source)

【讨论】:

  • 获得最大实用性和简洁性的奖品。
  • @piRSquared,一直在练习我的简洁性。角色很昂贵。
【解决方案2】:

不同之处在于元素的存储方式。

&lt;U12 将它们平铺存储,将每个条目补零至长度为 12。要看到这一点,我们可以使用 tobytes 直接访问数据缓冲区:

>>> au
array(['french', 'mexican', 'cajun_creole', 'Ellipsis', 'southern_us',
       'italian', 'thai'], dtype='<U12')
>>> 
>>> sz = au.dtype.itemsize
>>> [au.tobytes()[i:i+sz].decode('utf32') for i in range(0, au.size * sz, sz)]
['french\x00\x00\x00\x00\x00\x00', 'mexican\x00\x00\x00\x00\x00', 'cajun_creole', 'Ellipsis\x00\x00\x00\x00', 'southern_us\x00', 'italian\x00\x00\x00\x00\x00', 'thai\x00\x00\x00\x00\x00\x00\x00\x00']

object 只存储对象引用,即指向str 对象的指针。我们可以使用以下事实来验证这一点——在当前的 CPython 实现中——id 返回一个 Python 对象的内存地址:

>>> ao
array(['french', 'mexican', 'cajun_creole', Ellipsis, 'southern_us',
       'italian', 'thai'], dtype=object)
>>> 
>>> sz = ao.dtype.itemsize
>>> [int.from_bytes(ao.tobytes()[i:i+sz], 'little') for i in range(0, ao.size * sz, sz)]
[140626141129896, 140625895652128, 140625895628080, 8856512, 140625895627504, 140626141132200, 140626343518024]
>>> [id(it) for it in ao]
[140626141129896, 140625895652128, 140625895628080, 8856512, 140625895627504, 140626141132200, 140626343518024]

【讨论】:

    猜你喜欢
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 2013-10-15
    • 2011-01-27
    • 1970-01-01
    相关资源
    最近更新 更多