pandas str和object类型之间的区别

现象:

Numpy区分了str和object类型,其中dtype(‘S’)和dtype(‘O’)分别对应于str和object.

然而,pandas缺乏这种区别 str和object类型都对应dtype(‘O’)类型,即使强制类型为dtype(‘S’)也无济于事

>>> import pandas as pd
>>> import numpy as np
>>>
>>>
>>> np.dtype(str)
dtype('S')
>>> np.dtype(object)
>>>
>>>
dtype('O')
>>> df = pd.DataFrame({'a': np.arange(5)})
>>> df
   a
0  0
1  1
2  2
3  3
4  4
>>> df.a.dtype
dtype('int64')
>>> df.a.astype(str).dtype
dtype('O')
>>> df.a.astype(object).dtype
dtype('O')
>>> df.a.astype(str).dtype
dtype('O')

原理:

先说结论:

Numpy的字符串dtypes不是python字符串.pandas使用python字符串,.

numpy与pandas的字符串不同的含义:

>>> x = np.array(['Testing', 'a', 'string'], dtype='|S7')
>>> x
array([b'Testing', b'a', b'string'], dtype='|S7')
>>>
>>>
>>> y = np.array(['Testing', 'a', 'string'], dtype=object)
>>> y
array(['Testing', 'a', 'string'], dtype=object)

现在,一个是numpy字符串dtype(固定宽度,类似c的字符串),另一个原生python字符串数组.

如果我们试图超过7个字符,我们会看到立即的差异.numpy字符串dtype版本将被截断,而numpy对象dtype版本可以是任意长度

>>> x[1] = 'a really really really long'
>>> x
array([b'Testing', b'a reall', b'string'], dtype='|S7')
>>>
>>> y[1] = 'a really really really long'
>>> y
array(['Testing', 'a really really really long', 'string'], dtype=object)

尽管存在unicode固定长度字符串dtype,但| s dtype字符串不能正确地保持unicode

>>> z = x.view(np.uint8)
>>> z
array([ 84, 101, 115, 116, 105, 110, 103,  97,  32, 114, 101,  97, 108,
       108, 115, 116, 114, 105, 110, 103,   0], dtype=uint8)

猜你喜欢

转载自www.cnblogs.com/wqbin/p/12031083.html
今日推荐