Transforming a string list into a string array

Instead of creating new temporary arrays during iteration, assign values directly to the preallocated array. To achieve this, a solution is to preallocate a large numpy array, which can significantly speed up the process.


Solution:

Use

str.split

to process each item in the list.

newData = [item.split(',') for item in data] 


Demo:

>>> data = ['2014-01-31,46.83,48.55,46.80,48.03,3414400,48.03', '2014-01-30,47.47,48.11,47.29,48.00,2083900,48.00']
>>> newData = [item.split(',') for item in data] 
>>> newData[0][0]
'2014-01-31'
>>> newData[1][0]
'2014-01-30'

As has been suggested by previous commenters, the ideal approach would be to employ the

csv

module to extract information from the CSV file, assuming that the file includes:

2014-01-31,46.83,48.55,46.80,48.03,3414400,48.03
2014-01-30,47.47,48.11,47.29,48.00,2083900,48.00

This particular code will produce the expected result.

import csv
with open('file.csv') as f:
    reader = csv.reader(f)
    data = list(reader)

Frequently Asked Questions