【问题标题】:inplace replacement works for object but not string dtype就地替换适用于对象但不适用于字符串 dtype
【发布时间】:2020-08-31 15:41:42
【问题描述】:

对象 dtype 上的替换方法产生的结果与字符串 dtype 上的不同。我期待同样的结果。我在 Python 3.8.5 上运行 Pandas 1.1.0。

import pandas as pd
import numpy as np

a = pd.DataFrame({'a':['a','b','c'],'b':['d','','']},dtype='object')
b = pd.DataFrame({'a':['a','b','c'],'b':['d','','']},dtype='string')

print(a)
a.replace(r'^\s*$',pd.NA,regex=True,inplace=True)
print(a)

print(b)
b.replace(r'^\s*$',pd.NA,regex=True,inplace=True)
print(b)

   a  b
0  a  d
1  b   
2  c   
   a     b
0  a     d
1  b  <NA>
2  c  <NA>

   a  b
0  a  d
1  b   
2  c   
   a  b
0  a  d
1  b   
2  c   

【问题讨论】:

  • 我得到了相同的输出。空格替换为 NA。是的,更正一下,将b = pd.DataFrame({'a':['a','b','c'],'b':['d','','']},dtype='string') 中的'string' 更改为'str'。那么,您得到的输出是什么?
  • 这很奇怪,我得到了相同 sn-p 的替换值。您是否将 dtype 更改为 str
  • dtype='str' 创建 object dtype,而 dtype='string' 创建 stringDtype,这是我要使用的。

标签: python pandas dataframe replace


【解决方案1】:

这是一个已确认的错误。见https://github.com/pandas-dev/pandas/issues/35977

【讨论】:

    猜你喜欢
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 2017-01-06
    • 2019-12-23
    • 1970-01-01
    • 2017-03-25
    相关资源
    最近更新 更多