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
最后,numpy的字符串实际上是可变的,而Python字符串则不是.
>>> 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) >>> z+=1 >>> x array([b‘Uftujoh‘, b‘b!sfbmm‘, b‘tusjoh\x01‘], dtype=‘|S7‘)
由于所有这些原因,pandas选择不允许类似C的固定长度字符串作为数据类型.
正如所注意到的那样,尝试将python字符串强制转换为固定的numpy字符串将无法在pandas中使用.相反,它总是使用本机python字符串,对大多数用户来说,它的行为更直观.
原文:https://www.cnblogs.com/wqbin/p/12031083.html