pandas里面dtype的string object

当pandas使用read_csv读取CSV时,若第一列以字符开头,则数据类型为object,否则为int64。object类型在合并时可能导致错误,因为字符串长度不固定。pandas可能在未来支持新的文本存储方式,推荐使用str dtype来存储文本数据,以避免混合数据类型的问题并保持 dtype 特性的一致性。

今天写程序,遇到一个很有意思的情况

我的原始日志里,如果是下面这样的格式,第一行带字符开头。那么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:

  1. object -dtype NumPy array.

  2. StringDtype extension 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:

  1. You can accidentally store a mixture of strings and non-strings in an object dtype array. It’s better to have a dedicated dtype.

  2. object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text but still object-dtype columns.

  3. When reading code, the contents of an object dtype array is less clear than 'string'.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值