简体   繁体   English

用 None 替换 pandas 数据框中的值

[英]Replacing values in pandas data frame with None

This thread here shows replace with inplace=True to change values in pandas data frame.此线程此处显示replace为 inplace inplace=True以更改 pandas 数据框中的值。

I want to apply the same technique, but replacing with None我想应用相同的技术,但替换为None

mydf = pd.DataFrame({"col1":[5, 5, 8, 4, 5], "col2":[2, 5, 6, 7, 5]})
mydf.replace([5], None, inplace=True)

mydf changes like this and there is an additional output mydf像这样变化,还有一个额外的 output

   col1  col2
0     5     2
1     5     2
2     8     6
3     4     7
4     4     7
col1    None
col2    None
dtype: object

How to replace values with None ?如何用None替换值?

Prefer use pd.NA rather than None .更喜欢使用pd.NA而不是None Read this 读这个

mydf.replace([5], pd.NA, inplace=True)
# mydf.replace([5], [None], inplace=True)
>>> mydf
   col1  col2
0  <NA>     2
1  <NA>  <NA>
2     8     6
3     4     7
4  <NA>  <NA>

None also happens to be the default value for value argument so if you need to use it, you can place it in a 1-element list to distinguish that you're not passing the default: None也恰好是value参数的默认值,因此如果您需要使用它,您可以将它放在一个 1 元素列表中以区分您没有传递默认值:

mydf = mydf.replace([5], [None])

also: inplace=True is not so good , opt for assigning back另外: inplace=True不太好,选择返回

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM