Question

I have string final_line as

0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0130631958731,0.0,0.0,0.0,0.0,0.0,0.0,0.0130631958731,0.0,0.0,0.0,0.0,0.0,0.0,,
0.00507937313707,0.0,0.0,0.0201058520009,0.0,0.0,0.0459562331449,0.0268078026679,0.0,0.0103772139359,0.0,0.0,0.0438673134565,0.0,0.0268078026679,0.0,0.0,0.0,0.0,0.0,0.0224437417685,,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.070802847389,0.0,0.0,,
0.0,0.0,0.169140135429,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0261263917462,0.0,0.0,0.0,0.0,0.0,0.0,0.0261263917462,0.0,0.0,0.0,0.0,0.0,0.0,,
0.0961428138228,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,

I want to convert it into numpy array for without transferring to CSV file. Here each line in string should be converted to different row as

[['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0.08364751'], ['0.017944717', '0', '0', '0', '0.009470823', '0', '0', '0', '0', '0', '0'], ['0.012620501', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'], ['0.012620501', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0.01332164', '0', '0', '0', '0', '0', '0'], ['0.012620501', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0', '0.097414177', '0.042092545', '0', '0', '0', '0'], ['0', '0', '0', '0', '0.01332164', '0', '0', '0', '0', '0', '0'], ['0.005324215', '0', '0', '0.04598186', '0.028100025', '0', '0', '0', '0', '0', '0.023525603'], ['0', '0', '0', '0', '0', '0', '0', '0', '0.055765006', '0', '0'], ['0', '0', '0.133216404', '0', '0', '0', '0', '0', '0', '0', '0']]

I know here output having different values but I have just shown to get the format

Example

I have string as

a1,b1,c1,d1,e1,,
a2,b2,c2,d2,e2,,
a3,b3,c3,d3,e3,,

then output should be

[['a1','b1','c1','d1','e1'],
 ['a2','b2','c2','d2','e2'],
 ['a3','b3','c3','d3','e3']]

I have seen other questions but it converts into only single row of array. Here I want every single line in new row as shown in example.

Was it helpful?

Solution

map can be useful in this case. Also, the last ,, in your final list is not necessary so I just ignored it (look at :-2 before split operation).

import numpy as np

A = final_line[:-2].split(',,')
B = np.array([map(float,a.split(',')) for a in A])

OTHER TIPS

Your data is in the form of lists, with each line separated by an additional comma.

d_in = "1,2,3,,4,5,6,,7,8,9"
first = d_in.split(",,")
final = [line.split(",") for line in first]

first stores a list of strings (each of your columns). final stores your data in the proper format (in my example, [[1,2,3],[4,5,6],[7,8,9]])

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top