0

I am reviewing the following discussion

Plot a 2D graph from a csv file using matplotlib in Python in ubuntu

However, it does not fit quite well for my case. The data format in my .csv file is string. I used the following code to show this.

rm = np.genfromtxt('test.csv', delimiter=',',dtype='str', skip_header=26)
print(rm)
np.shape(rm)

enter image description here

If I want to plot the data with x-axis the left position in " ; ", and the y-axis the right position in " ; ". So I want the shape to be (1001,2). How to do this?

Thanks!

1 Answer 1

1

There are many ways to do this, but I would choose this way if I were you.

with open('matrix.txt') as file:
    lines = file.read()
# lines: '1;2;3;,4;5;6;,7;8;9;,'

lines = [line.split(';') for line in lines.split(',')]
# lines: [['1', '2', '3', ''], ['4', '5', '6', ''], ['7', '8', '9', ''], ['']]

lines = [[float(value) for value in line if value] for line in lines]
lines = [line for line in lines if line]
# lines: [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]

matrix = np.array(lines)
# matrix: array([[1., 2., 3.],
#                [4., 5., 6.],
#                [7., 8., 9.]])

Or, this way also could be your choice.

with open('matrix.txt') as file:
    lines = file.read()

lines = lines.replace(';', ' ').replace(',', ';')
# lines: '1 2 3 ;4 5 6 ;7 8 9 ;'

if lines[-1] == ';':
    lines = lines[:-1]

np.matrix(lines)

When saving your code, I think this would work too.

rm = np.genfromtxt('test.csv', delimiter=',', dtype='str', skip_header=26)
rm = np.array([[float(value) for value in line.split(';') if value] for line in rm])

They are not elegant, but they work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.