Ask Your Question

import csv file: integers appearing as floating points

asked 2013-05-20 03:17:16 -0500

GingerAndy gravatar image

updated 2013-05-20 09:11:27 -0500


I am trying to import a csv file in order to create an adjacency matrix and then plot the associated directed graph. I upload the csv file and use its content to generate a matrix as follows

sage: import csv                           
sage: data = list(csv.reader(file(DATA+'matrix23.csv')))
sage: m = matrix([[ float(_) for _ in line] for line in data])
sage: m

Whereas my csv file only contains integers 1's and 0's, the generated matrix is floating point 1.0's and 0.0's!

Note: the CSV file was created using MS Excel with cells formated to zero decimal places. I'm new to both python and sage and can't find anything on the forums to help

edit retag flag offensive close merge delete

3 answers

Sort by ยป oldest newest most voted

answered 2013-05-20 04:25:42 -0500

tmonteil gravatar image

updated 2013-05-20 04:33:45 -0500

If your matrix m only contains entries like 0.O and 1.0, you can try to transform it back to an integer matrix:

sage: n = m.change_ring(ZZ)

You can also transform your entries into integers while creating your matrix:

sage: m = matrix([[ ZZ(_) for _ in line] for line in data])
edit flag offensive delete link more

answered 2013-05-20 09:18:44 -0500


Note that in your code you use "float" to convert a string to a number. But by its very definition this function builds a floating point.

edit flag offensive delete link more

answered 2013-05-20 05:57:43 -0500

GingerAndy gravatar image

Thanks that works a treat.

edit flag offensive delete link more


Welcome to Sage! If you are pleased with Thierry answer then you should add it as a selected answer. Moreover this message to Thierry answer might be a comment within its answer (answer are somewhat reserved to *answer* the question and comments to *comment* about the questions or the answers). The last but not the least: you may select Thierry's answer as your selected answer in order to close this post!

vdelecroix gravatar imagevdelecroix ( 2013-05-20 09:18:40 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2013-05-20 03:17:16 -0500

Seen: 634 times

Last updated: May 20 '13