0

I want to read data in csv file and do some format. But I forget how to remove " ' ' " after I reformated the data into numpy array. I have seen that there is a trick to use eval() just in one line before. But I cannot find it now.

My csv file data looks like:

6,1 2 3 4 5 6 ... 2300 2301 2302 2303 2304\n

...

1,1 2 3 4 5 6 ... 2300 2301 2302 2303 2304\n

from load_data import load
import numpy as np
import matplotlib.pyplot as plt

with open('fer2013.csv') as f:
    f.readline()
    line = f.readline()
    line = line.replace("\n","")
    line = line.split(",")
    X = np.array(line[1].split(" "))
    X.reshape((48,48))
    print(X)

The output is:

[['70' '80' '82' ... '52' '43' '41'] ['65' '61' '58' ... '56' '52' '44'] ['50' '43' '54' ... '49' '56' '47'] ... ['91' '65' '42' ... '72' '56' '43'] ['77' '82' '79' ... '105' '70' '46'] ['77' '72' '84' ... '106' '109' '82']]

But what I want is :

[[70 80 82 ... 52 43 41] ... [77 72 84 ... 106 109 82]]

I have seen some tricks like this format (but actually it is not this):

X = np.array(for I in eval(line[1].split(" ")))

haofeng
  • 592
  • 1
  • 5
  • 21
  • Possible duplicate of [Read CSV file to numpy array, first row as strings, rest as float](https://stackoverflow.com/questions/12336234/read-csv-file-to-numpy-array-first-row-as-strings-rest-as-float) – user3053452 May 03 '19 at 15:19
  • I am still far from the numpy to slove my problem. I just want to use basic python operations. – haofeng May 03 '19 at 15:22

2 Answers2

1

Use X = np.array(line[1].split(" ")).astype(np.int)

0

OK, I found the answer.

X = np.array(list(map(eval,line[1].split(" "))))

haofeng
  • 592
  • 1
  • 5
  • 21