Sayan Mandal
Sayan Mandal

Reputation: 605

How to convert array of numbers saved as string in 'one' cell of a csv file in python?

p[1:2]
Out[23]: 
array([['[0.7856142  0.77921445 0.8273963  0.86992871 0.82833104 0.80677249\n 0.8410951  0.90299239 0.82401068 0.78761172 0.81294067 0.81446944]']],
      dtype=object)

This is one of the data I got from df.iloc[].values from cell.Spyder Variable Explorer says: Type: ndarray object of numpy. I want to convert to proper array of numbers. How shloud I do it? I've used p1=np.asfarray(p[1:2],float) and p1=pd.to_numeric(p[1:2], downcast = 'float') It shows raise TypeError.

Upvotes: 1

Views: 235

Answers (1)

Andy Hayden
Andy Hayden

Reputation: 375485

I would probably use a list comprehension:

In [11]: [[float(x) for x in item[1:-1].split()] for row in a for item in row]
Out[11]:
[[0.7856142,
  0.77921445,
  0.8273963,
  0.86992871,
  0.82833104,
  0.80677249,
  0.8410951,
  0.90299239,
  0.82401068,
  0.78761172,
  0.81294067,
  0.81446944]]

In future, you may like to use JSON serialization rather than string of the .values. For example:

In [21]: df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"])

In [22]: df.to_json()
Out[22]: '{"A":{"0":1,"1":3},"B":{"0":2,"1":4}}'

that way you can pd.read_json on the other side.

Upvotes: 2

Related Questions