【发布时间】: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