-2

there. I'm trying to remove quotations marks the following output

[['40' '40']
 ['10' '10']
 ['200' '200']
 ['230' '231']
 ['40' '43 ']
 ['15' '45 ']
 ['220' '190']]

I desire the following output:

[[40 40]
 [10 10]
 [....]]

here are my codes. I've been trying for a while but was unable to figure it out. If anyone can help, it will be highly appreciative.

import numpy as np
import matplotlib.pyplot as plt

def extract_file(file_name):
    file = open(file_name,'r')
    lines = ([line.strip("\n").split(",") for line in file])
    x= np.array(lines)
    return x
t= extract_file("backyard.txt")
Brandon Oson
  • 11
  • 1
  • 4
  • 3
    The quotes aren't in the data, they're shown because the array elements are strings. Convert them to numbers when creating the array. – Barmar Mar 30 '21 at 00:13
  • @Barmar No, the elements are integers, but when turned them into 2d array, the elements was turned into strings as well – Brandon Oson Mar 30 '21 at 00:23
  • No they aren't. `line.strip("\n").split(",")` returns a list of strings, not integers. – Barmar Mar 30 '21 at 00:25
  • No, you need to call `int()` on the elements after splitting. See my answer. – Barmar Mar 30 '21 at 00:30
  • Also see https://stackoverflow.com/questions/3518778/how-do-i-read-csv-data-into-a-record-array-in-numpy for reading a CSV directly into a numpy array. – Barmar Mar 30 '21 at 00:31

2 Answers2

0

@Barmar comments , np.genfromtxt could be use

import numpy as np
import matplotlib.pyplot as plt

def extract_file():
    return np.genfromtxt('test.txt',delimiter=',')
print(extract_file())

Output:

[[ 40.  40.]
 [ 10.  10.]
 [200. 200.]
 [230. 231.]
 [ 40.  43.]
 [ 15.  45.]
 [220. 190.]]

Its , Float , but i think it will works the same,

>>>type(numpy.genfromtxt('test.txt',delimiter=',')[0][0])
<class 'numpy.float64'>
Amirul Akmal
  • 401
  • 6
  • 13
  • If I were to input the file as file = open("backyard.txt", "r") i get an error saying that lines.append(int(line)) ValueError: invalid literal for int() with base 10: ',' – Brandon Oson Mar 30 '21 at 00:33
0

line.strip("\n").split(",") returns a list of strings, so you're creating an array of strings, not integers. Convert them to integers before creating the array.

lines = [list(map(int, line.strip("\n").split(","))) for line in file]
Barmar
  • 741,623
  • 53
  • 500
  • 612