JGW
JGW

Reputation: 334

replacing special characters in a numpy array with blanks

I have a list of lists (see below) which has ? where a value is missing:

([[1,2,3,4],
 [5,6,7,8],
 [9,?,11,12]])

I want to convert this to a numpy array using np.array(test), however, the ? value is causing an issue. What I want to do is replace the ? with blank space '' and then convert to a numpy array so that I have the following

so that I end up with the following array:

([[1,2,3,4],
 [5,6,7,8],
 [9,,11,12]])

Upvotes: 1

Views: 561

Answers (4)

Prakash Dahal
Prakash Dahal

Reputation: 4875

Python does not have type for ?

check this

a =?
print(type(a))

Above code will cause syntax error

It must be "?".

If this is the case then you can use

list1 = ([[1,2,3,4],
          [5,6,7,8],
          [9,?,11,12]])

for i1, ele in enumerate(list1):
  for i2, x in enumerate(ele):
    if x == "?":
      list1[i1][i2] = ""
print(list1)

Upvotes: 1

BeanBagTheCat
BeanBagTheCat

Reputation: 445

This is an approach using loops to find elements that can't be turned into integers and replaces them with blank spaces.

import numpy as np

preArray = ([[1,2,3,4],
            [5,6,7,8],
            [9,'?',11,12]])

newPreArray = []
for row in preArray:
    newRow = []

    for val in row:
        try:
            int(val)
            newRow.append(val)
        except:
            newRow.append('')

    newPreArray.append(newRow)

array = np.array(newPreArray)

Upvotes: 1

frab
frab

Reputation: 1173

Use list comprehension:

matrix = ...

new_matrix = [["" if not isinstance(x,int) else x for x in sublist] for sublist in matrix]

Upvotes: 2

I break things
I break things

Reputation: 326

For a single list you can do something like:

>>> myList = [4, 5, '?', 6]
>>> myNewList = [i if str(i).isdigit() else '' for i in myList]
>>> myNewList
[4,5,'',6]

so take that information and make it work with a list of lists.

Upvotes: 0

Related Questions