Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from CSV to array in Python

Tags:

python

csv

I have a CSV file containing the following.

0.000264,0.000352,0.000087,0.000549
0.00016,0.000223,0.000011,0.000142
0.008853,0.006519,0.002043,0.009819
0.002076,0.001686,0.000959,0.003107
0.000599,0.000133,0.000113,0.000466
0.002264,0.001927,0.00079,0.003815
0.002761,0.00288,0.001261,0.006851
0.000723,0.000617,0.000794,0.002189

I want convert the values into an array in Python and keep the same order (row and column). How I can achieve this?

I have tried different functions but ended with error.

like image 711
Edian Franklin Franco de los S Avatar asked May 11 '16 21:05

Edian Franklin Franco de los S


People also ask

How to read a CSV file into an array in Python?

Use numpy.loadtxt () to Read a CSV File Into an Array in Python As the name suggests, the open () function is used to open the CSV file. Numpy’s loadtxt () function helps in loading the data from a text file.

How to import CSV files into NumPy in data arrays?

This tutorial will introduce different methods to import CSV files in the form of data arrays. As the name suggests, the open () function is used to open the CSV file. Numpy’s loadtxt () function helps in loading the data from a text file.

How to get structured data from CSV file in Python?

The open () is a built-in function for file handling in Python. Then we need CSV.reader () to get structured data from.csv files. data_CSV = csv.reader (file_CSV) A list is the most used and convenient data structure in python so converting CSV files data into a list makes the data manipulation easy.

What are data arrays in CSV files?

These types of files are used to store data in the form of tables and records. In these tables, there are a lot of columns separated by commas. One of the tasks in manipulating these CSV files is importing these files in the form of data arrays.


2 Answers

You should use the csv module:

import csv

results = []
with open("input.csv") as csvfile:
    reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC) # change contents to floats
    for row in reader: # each row is a list
        results.append(row)

This gives:

[[0.000264, 0.000352, 8.7e-05, 0.000549], 
[0.00016, 0.000223, 1.1e-05, 0.000142], 
[0.008853, 0.006519, 0.002043, 0.009819], 
[0.002076, 0.001686, 0.000959, 0.003107], 
[0.000599, 0.000133, 0.000113, 0.000466], 
[0.002264, 0.001927, 0.00079, 0.003815], 
[0.002761, 0.00288, 0.001261, 0.006851], 
[0.000723, 0.000617, 0.000794, 0.002189]]
like image 164
MattDMo Avatar answered Oct 27 '22 23:10

MattDMo


If your file doesn't contain parentheses

with open('input.csv') as f:
    output = [float(s) for line in f.readlines() for s in line[:-1].split(',')]
    print(output);
like image 36
James Buck Avatar answered Oct 27 '22 22:10

James Buck