2

I need to create an array of strings, actually it is color value, for each value in another array. Logic is that for positive values should be one color, and for negatives another color.

I've tried this code snippet:

values = np.array([1, 2, -3, 4, 5])
color_values = np.array(['rgb(74,159,234)'] * len(values))
color_values[values < 0] = 'rgb(120,183,239)'
print(color_values)

But the problem is that new string values are truncating to length of previous value in array, so the result is:

['rgb(74,159,234)', 'rgb(74,159,234)', 'rgb(120,183,239', 'rgb(74,159,234)', 'rgb(74,159,234)']

THe third value is changed, but without last parethesis. I can rewrite code to achieve result I need but now I'm curious about why this happens.

I'm using Python 3.6, numpy 1.14.2

1
  • 1
    why to work with strings when we have tuples or numpy-array triplet? Commented Oct 12, 2018 at 13:38

1 Answer 1

1

Acording to this answer, str numpy arrays have a fixed length. They suggest specifying the data type when declaring the array.

You could try to add the datatype when declaring your array; set it to 16 chars (or more).

color_values = np.array(['rgb(74,159,234)'] * len(values), dtype='S16')

The rest of the lines should not need modification.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.