在 Pandas DataFrame 中用 None 替换无效值 [英] Replace invalid values with None in Pandas DataFrame
问题描述
有没有什么方法可以用 Python 中的 Pandas 中的 None
替换值?
您可以使用 df.replace('pre', 'post')
并且可以用另一个值替换一个值,但是如果您想用 None 替换,则不能这样做
值,如果你尝试,你会得到一个奇怪的结果.
这里有一个例子:
df = DataFrame(['-',3,2,5,1,-5,-1,'-',9])df.replace('-', 0)
返回一个成功的结果.
但是,
df.replace('-', None)
返回以下结果:
<预><代码>00 -//这不会被替换1 32 23 54 15 -56 -17 -1//改为`-1`...8 9为什么会返回这么奇怪的结果?
由于我想将此数据框倒入 MySQL 数据库,因此我不能将 NaN
值放入我的数据框中的任何元素中,而是想放入 None
.当然,您可以先将 '-'
更改为 NaN
,然后将 NaN
转换为 None
,但我想知道为什么数据框的行为如此糟糕.
在 Python 2.7 和 OS X 10.8 上的 pandas 0.12.0 dev 上测试.Python是一个OS X 上的预安装版本,我使用 SciPy 安装了 PandasSuperpack 脚本,供您参考.
实际上在以后的 pandas 版本中,这会导致 TypeError:
df.replace('-', None)类型错误:如果to_replace"和value"都是 None 那么正则表达式必须是一个映射
您可以通过传递列表或字典来实现:
在 [11]: df.replace('-', df.replace(['-'], [None]) # 或 .replace('-', {0: None})出[11]:00 无1 32 23 54 15 -56 -17 无8 9
但我建议使用 NaN 而不是 None:
在[12]中:df.replace('-', np.nan)出[12]:00 南1 32 23 54 15 -56 -17 纳米8 9
Is there any method to replace values with None
in Pandas in Python?
You can use df.replace('pre', 'post')
and can replace a value with another, but this can't be done if you want to replace with None
value, which if you try, you get a strange result.
So here's an example:
df = DataFrame(['-',3,2,5,1,-5,-1,'-',9])
df.replace('-', 0)
which returns a successful result.
But,
df.replace('-', None)
which returns a following result:
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
Why does such a strange result be returned?
Since I want to pour this data frame into MySQL database, I can't put NaN
values into any element in my data frame and instead want to put None
. Surely, you can first change '-'
to NaN
and then convert NaN
to None
, but I want to know why the dataframe acts in such a terrible way.
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.
Actually in later versions of pandas this will give a TypeError:
df.replace('-', None)
TypeError: If "to_replace" and "value" are both None then regex must be a mapping
You can do it by passing either a list or a dictionary:
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
But I recommend using NaNs rather than 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
这篇关于在 Pandas DataFrame 中用 None 替换无效值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!