Python Forum

Full Version: csv to array
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to save the .csv file data into array and than apply my logic

İmage


image shows the csv data
    import csv
    import matplotlib.pyplot as plt
    from numpy import *

    A = []
    B = []
    X = []

    f = open('1.csv')
    csv_f = csv.reader(f)

    for row in csv_f:
    B.append(row[0])
    A.append(row[1])
    X.append(row[2])
    a = 0
    b =1

    y = (a+(X-A)*(b-a))/(B-A)

    z = array([y])

    print (z)




while running this code I am getting an error



Error:
TypeError: unsupported operand type(s) for -: 'list' and 'list'

[Image: IiqQA.png]

csv data
That doesn't look like the entire error traceback, please post all.
I would suggest you to use Pandas for such data manipulations.
e.g.
import pandas as pd
data = pd.read_csv('your_file.csv') # check sep (separator) parameter 
data.values # numpy array
data['col1'] #access data by column names
It is very flexible and allows to perform basic operations with the data, e.g. filtering,
grouping, i/o, descriptive statistics, etc.
(May-16-2018, 01:49 AM)Larz60+ Wrote: [ -> ]That doesn't look like the entire error traceback, please post all.


Output:
Traceback (most recent call last): File "testdb.py", line 24, in <module> y = (a+(X-A)*(b-a))/(B-A) TypeError: unsupported operand type(s) for -: 'list' and 'list'

(May-16-2018, 01:53 AM)scidam Wrote: [ -> ]I would suggest you to use Pandas for such data manipulations. e.g.
 import pandas as pd data = pd.read_csv('your_file.csv') # check sep (separator) parameter data.values # numpy array data['col1'] #access data by column names
It is very flexible and allows to perform basic operations with the data, e.g. filtering, grouping, i/o, descriptive statistics, etc.
Quote:Thanks for the help!But I want to do it with numpy only
Error:
Traceback (most recent call last): File "testdb.py", line 24, in <module> y = (a+(X-A)*(b-a))/(B-A) TypeError: unsupported operand type(s) for -: 'list' and 'list'
This is not shown in the listing provided in post 1.

You need to make the lists numpy arrays (untested code, close if not working)
A1 = numpy.array(A)
X1 = numpy.array(X)
B1 = numpy.array(B)
y = (a+(X1-A1)*(b-a))/(B1-A1)
(May-16-2018, 04:03 AM)Vblaze10 Wrote: [ -> ].....
Thanks for the help!But I want to do it with numpy only

Let me tell you a secret - pd.DataFrame.values returns numpy.ndarray. Read CSV with pandas, get the ndarray - and you are set