0

I need to read this CSV to an array of floats. I'm new to python and unsure how to convert because when I read in the CSV it says that I am using type "Dictreader" hence why I am trying to convert. Thanks!

[Screenshot of where I'm at][1]

   import csv
    with open('NP.csv') as csvfile:
        NP = csv.DictReader(csvfile)
    with open('A.csv') as csvfule:
        A = csv.DictReader(csvfile)

    [r, c] = size(NP);
    [r2, c2] = size(A);

    for i in range(0, r):
        for j in range(0, c):
            NP(i,j) = float(NP(i,j));
    for i in range(0, r2):
        for j in range(0, c2):
            A(i,j) = float(A(i,j));
4
  • 1
    put your code and your input csv not an image of your code!!! Commented Mar 16, 2018 at 2:35
  • Please try doing some research before posting to StackOverflow. Otherwise, pandas read_csv might be exactly what you want. Commented Mar 16, 2018 at 2:44
  • 1
    Could you show a sample (maybe the first 10 lines or something) of NP.csv and/or A.csv? Commented Mar 16, 2018 at 3:18
  • Please add the function size() to your code. Commented Mar 20, 2018 at 14:46

1 Answer 1

1

If you are trying to read in a CSV file containing only floating point numbers, you could do this as follows:

import csv

def read_csv(filename):
    with open(filename, newline='') as f_input:
        return [list(map(float, row)) for row in csv.reader(f_input)]

NP = read_csv('NP.csv')
A = read_csv('A.csv')

So if NP.csv contained:

11.11,22.22,33.33,44.44
55.55,66.66,77.77,88.88

NP would now contain:

[[11.11, 22.22, 33.33, 44.44], [55.55, 66.66, 77.77, 88.88]]

Tested in Python 3.x

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.