1

I have an array of data and I would like to replace all the values that are greater than 50 with a string saying 'INDE'. How could I do this in python?

I tried this:

import numpy as np

row={'time': 10, 'tsys_1': [85.1, 91.8, 94.3, 37.1, 12.2, 17.4, 78.5, 68.8],'subarray': 1}

data=np.array(row['tsys_1'][0:8])

for i in range(len(data)):
    if data[i] > 50:
        data[i] = 'INDE'

But then this error occur:

ValueError: could not convert string to float: INDE

How can I do this?

1
  • Don't use np.array just data = row['tsys_1'][0:8] Commented Feb 27, 2014 at 17:01

1 Answer 1

3

It's probably better to just do this in pure python.

>>> row['tsys_1'] = ['INDE' if x > 50 else x for x in row['tsys_1']]
>>> row
{'subarray': 1,
 'time': 10,
 'tsys_1': ['INDE', 'INDE', 'INDE', 37.1, 12.2, 17.4, 'INDE', 'INDE']}

Having a numpy array which is a mixture of string and numbers kinda defeats the purpose of having a numpy array in the first place. However, if you really want that, here's how you could get it:

>>> data = np.array(row['tsys_1'][0:8]).astype(object)
>>> data[data > 50] = 'INDE'
>>> data
array(['INDE', 'INDE', 'INDE', 37.1, 12.2, 17.4, 'INDE', 'INDE'], dtype=object)

If you want to mask out these values in numpy, you might want to look at using a masked array (in numpy.ma) or use something like np.nan for your masked value instead of this string 'INDE'.

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

1 Comment

thank you, I used numpy.ma to mask this values and I get what I wanted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.