【问题标题】:dataframe string type cannot use replace method数据框字符串类型不能使用替换方法
【发布时间】:2021-10-26 05:34:21
【问题描述】:
df = pd.DataFrame({'a': ['asdf']}, dtype="string")
df["a"].replace({"a":"b"}, regex=True)

not chagend

df = pd.DataFrame({'a': ['asdf']}, dtype="object")
df["a"].replace({"a":"b"}, regex=True)

changed

我想将字符串值转换为其他值。 但是,如果我使用类型字符串,我不能使用替换方法。 如何更改字符串类型数据? 我应该使用对象类型吗?

【问题讨论】:

  • 我尝试了第一个代码,它成功了;将 a 更改为 b。熊猫 1.3 版
  • afternoon_drinker,你需要在字符串dtype上使用.str方法,详情请看答案。
  • @sammywemmy,谢谢。我用的是 1.2.4

标签: python pandas string dataframe


【解决方案1】:

对于字符串类型你可以这样做:

df = pd.DataFrame({'a': ['asdf']}, dtype="string")
df["a"].str.replace("a","b")

【讨论】:

  • 谢谢。在 df["a"].replace({"a":"b"}, regex=False) 的情况下怎么办
【解决方案2】:

如果您通过检查df.dtypes 发现差异,很明显您的数据类型最终是object,但列只是字符串,因此您需要应用pandas.Series.str.replace 才能获得结果。

但是,当您选择 dtype="object" 时,您的 dtype 和列数据仍然是 object,因此您不需要使用 .str 转换。

请查看source code,解释的很好:

要在系列或索引上调用 .str.{method},有必要 第一的 初始化:class:StringMethods对象,然后调用方法。

>>> df = pd.DataFrame({'a': ['asdf']}, dtype="string")
>>> df
      a
0  asdf

>>> df.dtypes
a    string
dtype: object

>>> df["a"].str.replace("a", "b", regex=True)
0    bsdf
Name: a, dtype: string
>>> df = pd.DataFrame({'a': ['asdf']}, dtype="object")
>>> df.dtypes
a    object
dtype: object

数据类型:

来自@HYRY。

看这里source of inspiration for below explanation

来自 All dtypes can now be converted to StringDtype 的 pandas 文档

dtype 对象来自 NumPy,它描述了 ndarray 中元素的类型。 ndarray 中的每个元素必须具有相同的字节大小。对于int64float64,它们是8 个字节。但是对于字符串来说,字符串的长度是不固定的。因此,Pandas 没有直接将字符串的字节保存在ndarray 中,而是使用了一个对象ndarray,它保存了指向对象的指针;因此,dtype 这种ndarray 是对象。

这是一个例子:

  • int64 数组包含 4 个 int64 值。
  • 对象数组包含 4 个指向 3 个字符串对象的指针。

注意:

Object dtype 的范围更广。它们不仅可以包含字符串,还可以包含 Pandas 不理解的任何其他数据。

【讨论】:

  • 谢谢。哪种类型更适合用于字符串操作?
猜你喜欢
  • 2012-09-25
  • 2017-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多