Ryan Ma
Ryan Ma

Reputation: 29

Python Convert 1-D array to N-D array

I am new to python and want to change the data from 1-D array to N-D array. Please see my sample data below:

a = array([['T-Shirts', '1 Piece'],
           ['Capris', 'Leggings', 'Skirts']], dtype=object)

and I want to get the data like:

array([[['T-Shirts'], ['1 Piece']],
       [['Capris'], ['Leggings'], ['Skirts']]], dtype=object)

Upvotes: 2

Views: 140

Answers (3)

Joseph Hansen
Joseph Hansen

Reputation: 13329

Set up

It looks like you're using the numpy package because your code has array(...) and dtype=... formatting. So, to prepare to show code examples, I did these commands:

import numpy as np
a = np.array([['T-Shirts', '1 Piece'], ['Capris', 'Leggings', 'Skirts']])

After those, when I enter:

a

I get this result (your starting point):

array([['T-Shirts', '1 Piece'], ['Capris', 'Leggings', 'Skirts']], dtype=object)

Desired output

When I do this command:

[[[x] for x in l] for l in a]

I get this result:

[[['T-Shirts'], ['1 Piece']], [['Capris'], ['Leggings'], ['Skirts']]]

The command I ran was a Python list comprehension. It is syntactic sugar for making a list with for loops. You can read more here or by searching for "python list comprehension".

Note: I did not use numpy for that conversion. If you want the same kind of list you had before, you could place the code inside np.array( ), like this:

np.array([[[x] for x in l] for l in a])

The result of that command is:

array([[['T-Shirts'], ['1 Piece']], [['Capris'], ['Leggings'], ['Skirts']]], dtype=object)

Bonus

Also, on a side note, you can do this:

[[x] for l in a for x in l]

and get this:

[['T-Shirts'], ['1 Piece'], ['Capris'], ['Leggings'], ['Skirts']]

Upvotes: 0

James
James

Reputation: 36756

Numpy does not support jagged arrays, which is what you are trying to get as your output. Your best bet is to move your data to native Python lists.

a = [['T-Shirts,1 Piece'], ['Capris,Leggings,Skirts']]
out = [[[y] for y in x[0].split(',')] for x in a]
out

# returns:
[[['T-Shirts'], ['1 Piece']], [['Capris'], ['Leggings'], ['Skirts']]]

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249582

It's easier using Pandas:

import pandas as pd
# note: removed useless sublists
x = ['T-Shirts,1 Piece', 'Capris,Leggings,Skirts']
pd.Series(x).str.split(',', expand=True)

That gives:

          0         1       2
0  T-Shirts   1 Piece    None
1    Capris  Leggings  Skirts

Upvotes: 1

Related Questions