今天写程序,遇到一个很有意思的情况
我的原始日志里,如果是下面这样的格式,第一行带字符开头。那么pandas read_csv读进来后,第一列的数据类型是object。
=>10000 E AUTO_JOB_CONTROL OK
91000 E INIT_BATCH OK
13000 P INIT_PRCSTS OK
12800 P INIT_FILCFG OK
如果改成下面这样的话,读进来就是int64
10000 E AUTO_JOB_CONTROL OK
91000 E INIT_BATCH OK
13000 P INIT_PRCSTS OK
12800 P INIT_FILCFG OK
如果meger的时候,object和int64这两个列为主键的话,就会报错了。
查询了下资料,原因如下。
原因:
因为字符串长度是不固定的,pandas没有用字节字符串的形式而是用了object ndarray
The dtype object comes from NumPy, it describes the type of element in a ndarray. Every element in a ndarray must has the same size in byte. For int64 and float64, they are 8 bytes. But for strings, the length of the string is not fixed. So instead of save the bytes of strings in the ndarray directly, Pandas use object ndarray, which save pointers to objects, because of this the dtype of this kind ndarray is object.
参考下文,未来有可能支持新的特性如下
https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html
There are two ways to store text data in pandas:
-
object-dtype NumPy array. -
StringDtypeextension type.
We recommend using StringDtype to store text data.
Prior to pandas 1.0, object dtype was the only option. This was unfortunate for many reasons:
-
You can accidentally store a mixture of strings and non-strings in an
objectdtype array. It’s better to have a dedicated dtype. -
objectdtype breaks dtype-specific operations likeDataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text but still object-dtype columns. -
When reading code, the contents of an
objectdtype array is less clear than'string'.
当pandas使用read_csv读取CSV时,若第一列以字符开头,则数据类型为object,否则为int64。object类型在合并时可能导致错误,因为字符串长度不固定。pandas可能在未来支持新的文本存储方式,推荐使用str dtype来存储文本数据,以避免混合数据类型的问题并保持 dtype 特性的一致性。

3137

被折叠的 条评论
为什么被折叠?



