简体   繁体   中英

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 ND 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)

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']]]

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

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']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM