realtacos
realtacos

Reputation: 3

Convert String to Array of Arrays in Python

I'm trying to convert what seems to be a string into an array of arrays. I'm uploading an excel sheet using read_excel but one of the columns is formatted:

[[u'MAKER', u'CREATED', u'1463538547', None], ['SHOP', u'ACCEPTED', u'1463538651', None], [u'SHOP', u'READY', u'1463539221', None], [u'COURIER', u'COMPLETED', u'1463540801', None]]

It's reading this as a complete string but I want it to be read as an array of arrays so I loop over each array. This is what I'm using to intake the file

changes = pd.read_excel('dataset.xlsx', sheet_name = "changes").

I tried changing the type to list but that doesn't seem to help.

Any help is greatly appreciated.

Thank You!

Upvotes: 0

Views: 884

Answers (2)

Stupid_designer
Stupid_designer

Reputation: 128

You can use ast.literal_eval

>>> from ast import literal_eval
>>> s = "['a',['b','c','d'],'e']"
>>> print(literal_eval(s))
['a', ['b', 'c', 'd'], 'e']

Upvotes: 2

1__
1__

Reputation: 1571

Can you try this? change 'array_column_name' to the actual column name

changes = pd.read_excel('dataset.xlsx', sheet_name = "changes",converters={'array_column_name':ast.literal_eval})

Upvotes: 0

Related Questions