简体   繁体   English

用 np.nan 替换列表中的所有值

[英]Replace all values in a list with np.nan

How to replace all values within a list with np.nan?如何用 np.nan 替换列表中的所有值?

a = [1.58, 2.13, 3.98, 4.12]

and what i want is我想要的是

a = [nan, nan, nan, nan]

I have tried many options like replace or list comprehension, but it didn't work.我尝试了许多选项,例如replace或列表理解,但没有奏效。

A numpy way of doing it natively: numpy 的原生方式:

a = np.full(shape=4, fill_value=np.nan).tolist()

Scales well to higher dimensions and larger size.可以很好地扩展到更高的尺寸和更大的尺寸。

import numpy as np
a = [1,2,3,4]
a = [np.nan]*len(a)
print(a)

Output: Output:

[nan, nan, nan, nan]
import numpy as np
a = np.full_like(a, np.nan).tolist()

If you want to update the existing list a then you can do this:如果你想更新现有的列表a那么你可以这样做:

a[:] = [np.nan] * len(a)

or even more efficiently - using a generator, rather than constructing a new list just for the assignment:甚至更有效 - 使用生成器,而不是仅仅为分配构造一个新列表:

a[:] = (np.nan for v in a)

But if you don't mind throwing a away and replacing it with a whole new list, then you can just do:但是,如果您不介意扔掉a并用一个全新的列表替换它,那么您可以这样做:

a = [np.nan] * len(a)

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

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