【问题标题】:pandas astype not recognize fix length bytestring formatpandas astype 无法识别固定长度的字节串格式
【发布时间】:2018-08-10 23:53:17
【问题描述】:

考虑以下示例:

df = pd.DataFrame([[1, "a"], [2, "b"]], columns=["int", "str"])
df.astype({"int":np.int8, "str": np.dtype('|S2')})
arr = df.to_records(index=False)
print(arr.dtype.descr)

我希望看到的是:

[(u'int', '<i8'), (u'str', '|S2')]

相反,我得到了:

[(u'int', '<i8'), (u'str', '|O')]

'|O' 的原因和含义是什么?

我也试过df.astype({"int":np.int8, "str": '|S2'}),得到了同样的结果。

【问题讨论】:

  • 表示输入Object

标签: python pandas numpy types


【解决方案1】:

表示输入objectfrom the docs

'O' (Python) 对象

创建 DataFrame 时,尽管指定了类型,但字符串的类型为 Object

df.dtypes

int     int64
str    object
dtype: object

astype 不是一个就地操作,所以你的命令目前什么都不做,你需要重新分配:

df = df.astype({"int":np.int8, "str": np.dtype('|S2')})

这仍然不会转换来自object 的字符串:

df.dtypes

int      int8
str    object
dtype: object

所以当你使用to_records 时,object 被使用而不是你指定的类型。

解决方法是单独创建您的字符串系列,并将其分配给您的 DataFrame:

s = pd.Series(['a', 'b'], dtype=np.dtype('|S2'))
df['d'] = s

df.dtypes

int      int8
str    object
d         |S2
dtype: object

并使用to_records

df.to_records(index=False)

rec.array([(1, b'a', b'a'), (2, b'b', b'b')],
          dtype=[('int', 'i1'), ('str', 'O'), ('d', 'S2')])

【讨论】:

  • 您能否在创建数据框时为列指定dtype
  • 您可以使用dtype 创建一个系列,例如pd.Series(['a', 'b'], dtype=np.dtype('|S2')) 的类型为bytes16。当我尝试在 DataFrame 构造函数中使用该类型时,我得到unrecognized datatype
  • So when you use to_records, object is used instead of your designated type. 所以我不能使用 |S2 类型来获取来自 pandas 的记录?
  • @buzhidao 我贴了一个解决方法,现在看看有没有更通用的解决方案
  • 先生成一条记录,然后将dtypes直接分配给该记录会更方便
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多