我试图从列表中删除'nan',但它拒绝去。我试过np.nan和'nan'。
这是我的代码:
ztt = []
for i in z:
if i != 'nan':
ztt.append(i)
ztt
或:
ztt = []
for i in z:
if i != np.nan:
ztt.append(i)
ztt
我仍然得到输出:
[[46.0, 34.0, 32.0, 40.0, 34.0, 29.0, 38.0, 39.0, 45.0, 32.0, 28.0, 43.0],
[32.0, 30.0, 67.0, 66.0, 28.0, 19.0, 39.0, 32.0, 51.0, 28.0, 20.0, 36.0],
[29.0, 24.0, 37.0, 31.0, 32.0, 34.0, 28.0, 31.0, 28.0, 33.0, 28.0, 39.0],
[27.0, 29.0, 35.0, nan, nan, nan, nan, nan, nan, nan, nan, nan]]
任何人都知道出了什么问题?
答案 0 :(得分:4)
for i in z:
if not math.isnan(i):
ztt.append(i)
答案 1 :(得分:3)
nan在你的情况下DOESN&T; T需要引号,coz nan是一个特殊的数字。当它被引用时它变成一个字符串类型。所以看起来应该是这样的:
ztt = []
for i in z:
if !math.isnan(i)
ztt.append(i)
ztt
或
ztt =[value for value in z if not math.isnan(value)]
答案 2 :(得分:2)
ztt = []
for z_i in z:
row = []
for z_ij in z_i:
if math.isnan(z_ij):
row.append(z_ij)
# If you want to replace with, for example, 0:
# else:
# row.append(0)
ztt.append(row)
或者,使用嵌套列表推导:
ztt = [[z_ij for z_ij in zi if math.isnan(z_ij)] for z_i in z]
顺便说一下,如果您使用的是NumPy,您可能只会这样做:
import numpy as np
ztt =[value[~np.isnan(value)] for value in z]
答案 3 :(得分:2)
您的代码的主要问题是,np.nan != np.nan
是True
您也可以考虑使用数组而不是列表。
import numpy as np
z = np.array(z) #convert into array, which allows other indexing
ztt = z[np.logical_not(np.isnan(z))]
答案 4 :(得分:1)
为什么不在for循环中使用,即
k = [[46.0, 34.0, 32.0, 40.0, 34.0, 29.0, 38.0, 39.0, 45.0, 32.0, 28.0, 43.0],
[32.0, 30.0, 67.0, 66.0, 28.0, 19.0, 39.0, 32.0, 51.0, 28.0, 20.0, 36.0],
[29.0, 24.0, 37.0, 31.0, 32.0, 34.0, 28.0, 31.0, 28.0, 33.0, 28.0, 39.0],
[27.0, 29.0, 35.0, 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan']]
for i,j in enumerate(k):
while 'nan' in k[i]: k[i].remove('nan')
输出:
[[46.0, 34.0, 32.0, 40.0, 34.0, 29.0, 38.0, 39.0, 45.0, 32.0, 28.0, 43.0], [32.0, 30.0, 67.0, 66.0, 28.0, 19.0, 39.0, 32.0, 51.0, 28.0, 20.0, 36.0], [29.0, 24.0, 37.0, 31.0, 32.0, 34.0, 28.0, 31.0, 28.0, 33.0, 28.0, 39.0], [27.0, 29.0, 35.0]]
m = [[46.0, 34.0, 32.0, 40.0, 34.0, 29.0, 38.0, 39.0, 45.0, 32.0, 28.0, 43.0],
[32.0, 30.0, 67.0, 66.0, 28.0, 19.0, 39.0, 32.0, 51.0, 28.0, 20.0, 36.0],
[29.0, 24.0, 37.0, 31.0, 32.0, 34.0, 28.0, 31.0, 28.0, 33.0, 28.0, 39.0],
[27.0, 29.0, 35.0,np.nan,np.nan,np.nan,np.nan,np.nan]]
for i,j in enumerate(m):
while np.nan in m[i]: m[i].remove(np.nan)
输出:
[[46.0, 34.0, 32.0, 40.0, 34.0, 29.0, 38.0, 39.0, 45.0, 32.0, 28.0, 43.0], [32.0, 30.0, 67.0, 66.0, 28.0, 19.0, 39.0, 32.0, 51.0, 28.0, 20.0, 36.0], [29.0, 24.0, 37.0, 31.0, 32.0, 34.0, 28.0, 31.0, 28.0, 33.0, 28.0, 39.0], [27.0, 29.0, 35.0]]