Home > Software design >  Reading data from a csv file python
Reading data from a csv file python

Time:04-02

I have a csv file with the following data stored as uncov_users.csv: 2867,2978

I am trying to get the data from the CSV file and print it but I am getting an error. I need the data in separate variables so I am using the for i,j loop.

My Code:

import numpy as np
uncov_users = np.genfromtxt('ucov_users.csv', delimiter=',')
for i,j in uncov_users:
    ux_coor = i  
    uy_coor = j  
    print(ux_coor,uy_coor)

Error:

Traceback (most recent call last):
  File "D:\Programmes\Final_Year\Plot_DFO\test.py", line 3, in <module>
    for i, j in uncov_users:
TypeError: cannot unpack non-iterable numpy.float64 object

I am just trying to understand what is wrong with it and how can it be fixed.

CodePudding user response:

Use pandas. You can put you csv in a dataframe, then convert you columns into numpy arrays :

import pandas
import numpy as np

dataframe = pandas.read_csv('ucov_users.csv', delimiter=',')
ux_coord = np.array(dataframe.iloc[:, 0])
uy_coord = np.array(dataframe.iloc[:, 1])

CodePudding user response:

Use:

  for row in uncov_users:
    ux_coor, uy_coor = row
    print(ux_coor,uy_coor)
  • Related