0

I have the following list that contains integers and nan values:

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]

I want to join the integers in order to become one number and the nan values to remain in their position. Also, each new number should contain 6 digits.

The new list should look like this:

x = [883329, nan, nan, nan, 419482, nan, nan, nan, nan, 221112, nan, nan, nan, nan, 419583, 888342, nan]

I tried the following code, but it's not what I want

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]

Any suggestions on how to fix this?

OnebyOne
  • 57
  • 4

1 Answers1

1

You could do the following, using groupby and the grouper recipe:

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)

Output

[883329, nan, nan, nan, 419482, nan, nan, nan, nan, 221112, nan, nan, nan, nan, 419583, 888342, nan]
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76