powerPixie
powerPixie

Reputation: 708

Choose how to flatten an array (python)

This is a sample of the array I am dealing with:

    records = [[[['   1'], ['   2'], ['   3'], ['   4']]], [[['   red'], ['   blue'], ['   black'], ['   white']]]]

I want to end up with a structure like this one:

    [['   1','   2','   3','   4'],['   red','   blue','   black','   white']]

I've tried the following:

    levelOne = [recs for sublist in records for recs in sublist]
    final = [recs for sublist in levelOne for recs in sublist]

And what I've got was:

    [['   1'], ['   2'], ['   3'], ['   4'], ['   red'], ['  blue'], ['   black'], ['   white']]

Upvotes: 1

Views: 81

Answers (3)

Mykola Zotko
Mykola Zotko

Reputation: 17794

You can use the method reshape:

records = np.array(records)
records = records.reshape(2, -1)

print(records)

Output:

array([['   1', '   2', '   3', '   4'],
       ['   red', '   blue', '   black', '   white']], dtype='<U8')

Upvotes: 1

mcsoini
mcsoini

Reputation: 6642

Use the built-in itertools.chain.from_iterable for flattening/chaining. Then it's just a matter of applying to the right nested list level:

import itertools
list(list(itertools.chain.from_iterable(rec[0])) for rec in records)

[['   1', '   2', '   3', '   4'],
 ['   red', '   blue', '   black', '   white']]

Or as a single list comprehension

[[r[0] for r in rec[0]] for rec in records]

[['   1', '   2', '   3', '   4'],
 ['   red', '   blue', '   black', '   white']]

Or if your nested list is a numpy array to begin with, you can use numpy.reshape:

np.reshape(np.array(records), (2, 4))

array([['   1', '   2', '   3', '   4'],
       ['   red', '   blue', '   black', '   white']], dtype='<U8')

Upvotes: 1

Akash Kumar
Akash Kumar

Reputation: 301

If your records array is numpy array then remove np.array(records) just put records If you want simple list then remove np.array casting in np.array(list(...)) in res

import numpy as np
res=np.array(list(map(lambda x : x.reshape(-1), np.array(records))))

Upvotes: 1

Related Questions