0

我已经开始在 pandas 1.0.1 中使用 StringDtype 我知道它被认为是实验性的,但是在包含 NaN 的字符串类型列上使用替换时遇到了问题。

例如:

df = pd.DataFrame({'a': ['a', 'b', 'c', None]}, dtype='string')
df.replace({'c': 'e'})

上述结果:

TypeError: Cannot compare types 'ndarray(dtype=object)' and 'str'

这可能是一个错误还是我做错了什么?

4

1 回答 1

0

尝试这个:

import pandas as pd

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

df.replace('c', 'e', inplace=True)
print(df)

你会得到:

      a
0     a
1     b
2     e
3  <NA>

或者如果您想保留dictas to_replace 值,您首先需要:

list = ['a', 'b', 'c', np.nan]
s = pd.Series(list)
df = pd.DataFrame({'a': s})    

df.replace({'c': 'e'}, inplace=True)
print(df)

输出:

     a
0    a
1    b
2    e
3  NaN

无法真正解释它为什么起作用,即使已经阅读了文档

于 2020-04-10T10:27:25.320 回答