-3

I stored 2D numpy arrays into a pandas dataframe, which I stored into a csv file. While reading the csv file, I am struggling to get back my 2D numpy array as they are stored as type string... How could I get the numpy array that is inside the string?

For example I have '[1.34 5.43]' and I want to convert to [1.34 5.43]. Any way to convert numpy array interpreted as string into numpy array?

SOLUTION: This was the solution How to convert string representation of list to a list?

4

1 Answer 1

0

You can use the genfromtxt function.

import numpy as np
#create the array 
arr=np.arange(20).reshape(4,5)
#save as a text file
np.savetxt("arr.csv", arr, delimiter=",")
from numpy import genfromtxt
#generate array from text file
my_data = genfromtxt('arr.csv', delimiter=',')
type(my_data)

Output

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

5 Comments

That's not exactly what I want. The numpy arrays are stored as string in the csv file. When I load the csv file, I want that each cell to be interpreted as a numpy array and not as a string
How does your csv file looks like ? Here the csv file is in string but genfromtxt converts into a numpy array type.
I don't want to store all the values as a numpy array. I want to load my values in a pandas dataframe with each value being a numpy array
@user7924113 I think without any reproducible example of input and output it will be a bit hard to understand your problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.