我有以下包含整数和nan值的列表:
x = [8, 8, 3, 3, 2, 9, nan, nan, nan, 4, 1, 9, 4, 8, 2, nan, nan, nan, nan, 2, 2, 1, 1, 1, 2, nan, nan, nan, nan, 4, 1, 9, 5, 8, 3, 8, 8, 8, 3, 4, 2, nan]
我想加入整数以成为一个数字,并将nan值保持在其位置。另外,每个新数字都应包含6位数字。
新列表应如下所示:
x = [883329, nan, nan, nan, 419482, nan, nan, nan, nan, 221112, nan, nan, nan, nan, 419583, 888342, nan]
我尝试了以下代码,但这不是我想要的
y =''.join(str(n) for n in x)
k=list(map(''.join, zip(*[iter(y)]*6)))
k = [883329, nannan, nan419, 482nan, nannan, nan221, 112nan, nannan, nan419, 583888, 342nan]
关于如何解决此问题的任何建议?
答案 0 :(得分:1)
from numpy import nan, isnan
from itertools import groupby, zip_longest
x = [8, 8, 3, 3, 2, 9, nan, nan, nan, 4, 1, 9, 4, 8, 2, nan, nan, nan, nan, 2, 2, 1, 1, 1, 2, nan, nan, nan, nan, 4, 1,
9, 5, 8, 3, 8, 8, 8, 3, 4, 2, nan]
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(fillvalue=fillvalue, *args)
result = []
for k, v in groupby(x, key=isnan):
if k:
result.extend(list(v))
else:
result.extend(int(''.join(g)) for g in grouper(6, map(str, v)))
print(result)
输出
[883329, nan, nan, nan, 419482, nan, nan, nan, nan, 221112, nan, nan, nan, nan, 419583, 888342, nan]