Reputation: 812
I have this piece of code:
csvData = np.array([]);
csvData = np.append(csvData, ['1', '2016-01-01', 'Some text'])
csvData = np.append(csvData, ['2', '2016-01-02', 'Some more text'])
print(csvData)
it outputs: ['1' '2016-01-01' 'Some text' '2' '2016-01-02' 'Some more text']
I would like to get something like:
[['1' '2016-01-01' 'Some text'], ['2' '2016-01-02' 'Some more text']]
I tried wrapping my data string into []
. The reason I am doing this, because I want to collect each csv row, sort it by specific column and iterate data rows.
Any other solution is welcome.
I would sort using something like: csvData [np.argsort(csvData [:,2])]
Upvotes: 0
Views: 6214
Reputation: 4499
Before I give the solution please take look at why you should not build not repeatedly append to numpy arrays.
Having said that if you must do it (it very very inefficient and highly discouraged) here is how it can be done
>>> import numpy as np
>>> r1 = ['1', '2016-01-01', 'Some text']
>>> r2 = ['2', '2016-01-02', 'Some more text']
>>> ar = np.empty(shape=(0,3))
>>> ar = np.vstack( [ar, r1] )
>>> ar = np.vstack( [ar, r2] )
>>> ar
array([['1', '2016-01-01', 'Some text'],
['2', '2016-01-02', 'Some more text']],
dtype='<U32')
note: pands library built over numpy may be more suitable for your needs. It provides function to read CSV files pandas.read_csv
Upvotes: 1
Reputation: 1441
Your desired output is a list of list which can be generated by the below code:
csvData = []
csvData.append(['1', '2016-01-01', 'Some text'])
csvData.append(['2', '2016-01-02', 'Some more text'])
#csvData would be
#[['1', '2016-01-01', 'Some text'], ['2', '2016-01-02', 'Some more text']]
But since you use numpy library, for converting it to the appropriate type this line helps:
csvData = np.asarray(csvData)
#csvData would be
[['1' '2016-01-01' 'Some text']
['2' '2016-01-02' 'Some more text']]
Upvotes: 3
Reputation: 987
You can try to save np.append
in subarray and then append it to main array. Something like that:
array = []
subarray = ['1', '2016-01-01', 'Some text']
...
array.append(subarray)
Don't know what object np
is.
Upvotes: 1