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:
Try this:
import numpy as np
text = open("ucov_users.csv", "r")
text = ''.join([i for i in text]) \
.replace(" ", "\n")
x = open("ucov_users.csv", "w")
x.writelines(text)
x.close()
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)
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:
Your uncov_users
variable is the wrong shape. For the loop
for i,j in uncov_users:
# stuff ...
to work, uncov_users
would need to be a 2d array with two columns, so that i
could be assigned a value from the first column and j
a value from the second columm.
This problem would be easier to see if you rewrote your for
loop like this:
for row in uncov_users:
i,j = row
# stuff ...
For the uncov_users
array that you have, row
is just a number (or to be precise, a numpy.float64
object), so it can't be unpacked. It doesn't have two components that could be assigned to the variables i
and j
.
Probably the simplest way to fix this would be to use the numpy.atleast_2d()
function, e.g,
uncov_users = np.atleast_2d(np.genfromtxt('ucov_users.csv', delimiter=','))
This way, if the file ucov_users.csv
has only one row with two columns, the array uncov_users
will still have two columns, instead of being a 1d array with two elements. (Of course, this assumes that ucov_users.csv
always has two columns.)
CodePudding user response:
Use:
for row in uncov_users:
ux_coor, uy_coor = row
print(ux_coor,uy_coor)