有没有什么方法可以在 Python 中的 Pandas 中用 None
替换值?
您可以使用 df.replace('pre', 'post')
并且可以将一个值替换为另一个值,但是如果您想用 None 替换,则无法这样做
值,如果你尝试,你会得到一个奇怪的结果。
下面是一个例子:
df = DataFrame(['-',3,2,5,1,-5,-1,'-',9])
df.replace('-', 0)
返回一个成功的结果。
但是,
df.replace('-', None)
返回以下结果:
0
0 - // this isn't replaced
1 3
2 2
3 5
4 1
5 -5
6 -1
7 -1 // this is changed to `-1`...
8 9
为什么会返回这么奇怪的结果?
由于我想将此数据框放入 MySQL 数据库中,因此我无法将 NaN
值放入数据框中的任何元素中,而是希望放入 None
。当然,您可以先将 '-'
更改为 NaN
,然后将 NaN
转换为 None
,但我想知道为什么数据框的行为如此糟糕。
Tested on pandas 0.12.0 dev on Python 2.7 and OS X 10.8. Python is a pre-installed version on OS X and I installed pandas by using SciPy Superpack script, for your information.
最佳答案
实际上在更高版本的 pandas 中,这会产生 TypeError:
df.replace('-', None)
TypeError: If "to_replace" and "value" are both None then regex must be a mapping
您可以通过传递列表或字典来做到这一点:
In [11]: df.replace('-', df.replace(['-'], [None]) # or .replace('-', {0: None})
Out[11]:
0
0 None
1 3
2 2
3 5
4 1
5 -5
6 -1
7 None
8 9
但我建议使用 NaN 而不是 None:
In [12]: df.replace('-', np.nan)
Out[12]:
0
0 NaN
1 3
2 2
3 5
4 1
5 -5
6 -1
7 NaN
8 9
关于python - 在 Pandas DataFrame 中用 None 替换无效值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17097236/