BadProgrammer
BadProgrammer

Reputation: 99

String to np.matrix back to string

I read a string data from a TCP port and it looks like this:

data_string = '1,1.0,2.4,4,3,0.0,0.0,0.0,7,-2.5,80,1481307702.180;2,3.3,10.1,2,2,0.0,-0.0625,-0.25,7,-20.0,3,1481307702.180;3,-0.2,1.5,4,4,0.0,0.0,0.0,7,-7.0,80,1481307702.180;4,-3.7,25.4,2,1,-0.0625,0.0,0.0,7,19.5,3,1481307702.180;5,-3.2,5.8,4,4,-0.0625,0.0,0.0,7,-5.0,39,1481307702.180;6,2.2,13.4,2,2,0.0,0.0,-0.25,6,-24.5,3,1481307702.180;7,-2.4,19.9,2,1,0.0,0.0625,0.0,7,-23.0,5,1481307702.180;8,0.0,0.0,0,0,0.0,0.0,0.0,1,0.0,0,1481307702.180;9,0.6,7.7,4,3,0.0625,0.0625,0.0,7,-18.5,6,1481307702.180'

I use np.matrix(data_string) to put the data into a numpy matrix.

After doing some manipulation of the data, I want to put it back in the same string format. Any advice?

Upvotes: 1

Views: 73

Answers (1)

user6655984
user6655984

Reputation:

If m is a matrix, the following will convert it to a string of the specified format:

new_string =  ";".join([",".join(map(str, row)) for row in m.tolist()])

I tested with your data; the output is nearly the same as original data_string, except for 1 becoming 1.0 (but your 1 was a float anyway, so this should be fine).

Upvotes: 1

Related Questions